首页 > 解决方案 > 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;")通过脚本执行时,它挂在这个请求上并且不返回任何内容并且没有错误。

标签: python-3.xselenium-webdriverwebdriver

解决方案


您可以尝试在滚动之前等待页面完全加载。为此,您可以使用下面的代码等待 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")))

推荐阅读