python-3.x - Python:Webdriver 向下滚动页面停止工作
问题描述
我已经使用以下功能向下滚动页面 2 年多了,在 2019 年 12 月 31 日它刚刚停止工作,没有错误,只是停止向下滚动。
我正在使用 Chrome 版本 79.0.3945.88 和 ChromeDriver 2.36.540470。非常感谢任何想法或帮助。
def scrollToEndOfPage(self, driver):
try:
time.sleep(1)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight;")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(randint(2,4))
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight;")
if new_height == last_height:
break
last_height = new_height
except Exception as e:
print(str(e))
更新:1
我已经document.body.scrollHeight;
在有问题的网站(内部网站)上运行,它显示页面高度,但是当我尝试driver.execute_script("return document.body.scrollHeight;")
通过脚本执行时,它挂在这个请求上并且不返回任何内容并且没有错误。
解决方案
您可以尝试在滚动之前等待页面完全加载。为此,您可以使用下面的代码等待 JavaScript 完成:
from selenium.webdriver.support.ui import WebDriverWait
# ...
WebDriverWait(browser, 30).until(lambda d: d.execute_script(
'return (document.readyState == "complete" || document.readyState == "interactive")'))
或使用WebDriverWait
并等待特定元素/元素的可见性/可点击性,如下所示:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_all_elements_located((By.XPATH, "some elements on locator")))
# or
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "some clickable element locator")))
推荐阅读
- amazon-web-services - AWS 弹性负载均衡器(公共到内部)
- webpack - webpack 托管捆绑文件的位置。视窗
- php - 为数据库中的每条记录创建 WAV 文件
- jasperserver - 在 JasperReports 服务器 7.1 中获取休息/登录调用的 404 响应
- javascript - 如何从后效扩展脚本中使用nodejs获取退出代码?
- amazon-web-services - 如何避免 redshift 卸载命令中的重复行
- google-app-engine - 如何在 google-app-engine nginx 中增加 fastcgi_read_timeout?
- c# - 无法保存图像对象
- c++ - 使用 libusb.h 时出现编译器错误
- html - 寻找可以修复数据类型冲突问题的 html 输入属性或引导类