【问题标题】:Selenium scroll down slowlySelenium 慢慢向下滚动
【发布时间】:2019-05-07 14:27:58
【问题描述】:

我正在尝试使用 Python 在 javascript 呈现的网页上进行动态网页抓取。

1) 但是,只有当我慢慢向下滚动页面时才会加载元素。

我试过了:

driver.execute_script("window.scrollTo(0, Y)") 

(这不起作用,因为它只滚动到页面上的某个点,错过了其他结果)

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

(这不起作用,因为向下滚动到页面末尾时元素不会加载 - 它需要用户慢慢滚动整个页面)

2) 如何让 Selenium 等待我的所有元素加载完毕,然后再将它们返回给我?

我了解存在此解决方案:

myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))

但是,如果结果在用户向下滚动页面时不断出现,这将如何工作?一旦检测到所述元素的第一次出现,这段代码不会让 Selenium 停止吗?

【问题讨论】:

  • 你滚动几次怎么样,在滚动之间等待?
  • 如果您正在寻找任何特定记录并知道您想要的记录数?如果答案是肯定的,那么我们可以使用location_once_scrolled_into_view 处理这个问题

标签: python selenium web screen-scraping


【解决方案1】:

您可以编写一个向下发送箭头键的函数,直到您可以找到该元素。最好在通过某种FluentWait(这是一个java类)完成的循环中,但我也在Python中看到过这个:python fluent wait 目标是在设定的时间内继续向下发送箭头键,同时忽略NoSuchElementException

【讨论】:

    【解决方案2】:

    这可能对你有帮助

        SCROLL_PAUSE_TIME = 0.5 
        # 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(SCROLL_PAUSE_TIME)
    
            # 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
    

    您可以将此代码与此功能结合使用:

    myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
    

    【讨论】:

      【解决方案3】:

      使用execute_async_script慢慢向下滚动到页面末尾:

      driver.execute_async_script(
                  """
              count = 400;
              let callback = arguments[arguments.length - 1];
              t = setTimeout(function scrolldown(){
                  console.log(count, t);
                  window.scrollTo(0, count);
                  if(count < (document.body.scrollHeight || document.documentElement.scrollHeight)){
                    count+= 400;
                    t = setTimeout(scrolldown, 1000);
                  }else{
                    callback((document.body.scrollHeight || document.documentElement.scrollHeight));
                  }
              }, 1000);"""
              )
      

      【讨论】:

        猜你喜欢
        • 2015-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多