Python:Webdriver向下滚动页面停止工作

问题描述 投票:0回答:1

[我一直在使用以下功能向下滚动页面超过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.x selenium-webdriver webdriver
1个回答
0
投票

您可以尝试在滚动之前等待页面完全加载。为此,您可以使用下面的代码等待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")))
© www.soinside.com 2019 - 2024. All rights reserved.