如何解决在 python 中使用 selenium 滚动页面,只给我底部元素
我有页面,但我需要滚动页面并一一获取元素。 我正在使用以下命令:
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
但这段代码滚动到底部,只给我最后一个元素,但我需要上面的所有元素
我也在使用这个代码这个代码,但结果是一样的。我如何提取所有元素,而不是顶部或最后一个
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_height = driver.execute_script("return document.body.scrollHeight")
elll.append(el.find_elements(By.XPATH,'//div[contains(@class,"ProductItemWrapper")]'))
if new_height == last_height:
break
last_height = new_height
elll=el.find_elements(By.XPATH,"ProductItemWrapper")]')
是否存在另一种滚动页面并抓取所有元素的方法,而不是顶部或底部元素?
解决方法
逐页滚动完成,而不是一次滚动整个页面高度。
例如你可以使用这个:driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
document.body.scrollHeight
给出整个页面的滚动高度。因此,它立即向下滚动到底部。因此,每次使用 window.scrollY
获取当前滚动位置并仅向下滚动视口高度 window.innerHeight
。
last_height = driver.execute_script("return window.scrollY")
elll=[]
while True:
driver.execute_script("window.scrollTo(0,window.scrollY + window.innerHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_height = driver.execute_script("return window.scrollY")
elll.append(el.find_elements(By.XPATH,'//div[contains(@class,"ProductItemWrapper")]'))
if new_height == last_height:
break
last_height = new_height
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。