我正在尝试获取页面上的所有元素,但是它具有无限滚动的功能。我尝试向下滚动页面,然后获取属性,但没有将它们全部都拿走吗?由于某种原因,我只能得到其中的一半?
driver = webdriver.Firefox()
driver.get("http://www.amazon.com/gp/pdp/profile/A2A46BUQRGSAB0/ref=cm_cr_dp_pdp")
lastHeight = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
newHeight = driver.execute_script("return document.body.scrollHeight")
print newHeight, lastHeight
if newHeight == lastHeight:
break
lastHeight = newHeight
tree = etree.HTML(driver.page_source)
product = tree.xpath('//span[@class="a-size-base product-title pr-multiline-ellipses-container"]//text()')[::3]
print len(product)
您需要等待滚动生效。否则,您将在更新完成之前获取源代码。
简单但不完美的解决方法是使用time.sleep
足够的时间:
import time
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1) # <---
newHeight = driver.execute_script("return document.body.scrollHeight")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句