代码之家  ›  专栏  ›  技术社区  ›  llanato

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

  •  0
  • llanato  · 技术社区  · 6 年前

    我使用下面的功能向下滚动页面已经两年多了,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;") 通过一个脚本,它挂起这个请求,不返回任何内容,也没有错误。

    0 回复  |  直到 6 年前
        1
  •  0
  •   Sers    6 年前

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