【问题标题】:Scroll to the end of the infinite loading page using selenium Python使用 selenium Python 滚动到无限加载页面的末尾
【发布时间】:2020-12-18 05:13:58
【问题描述】:

我正在使用 Selenium 从 twitter 上抓取关注者姓名,并且该页面是无限的,每当我向下滚动时,我都可以看到新的关注者。 不知何故,我想转到页面底部,以便我可以抓取所有关注者。

while number != 5:
   driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
   number = number + 1
   time.sleep(5)

usernames = driver.find_elements_by_class_name(
       "css-4rbku5.css-18t94o4.css-1dbjc4n.r-1loqt21.r-1wbh5a2.r-dnmrzs.r-1ny4l3l")
for username in usernames:
   print(username.get_attribute("href"))

现在代码滚动了 5 次。我放了一个静态值,但我不知道需要多少滚动才能到达页面底部。

【问题讨论】:

    标签: selenium selenium-chromedriver


    【解决方案1】:

    使用下面的代码进行无限加载。它会一直滚动,直到新元素被加载,即页面大小发生变化。

    # Get scroll height after first time page load
    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(2)
        # 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
    

    【讨论】:

      【解决方案2】:

      在以下脚本中,没有睡眠时间,因此滚动速度更快:

      SCROLL_PAUSE_TIME = 4
      last_height = driver.execute_script("return document.body.scrollHeight")
      while True:
          import datetime
          time_past = datetime.datetime.now()
          while (datetime.datetime.now() - time_past).seconds <=SCROLL_PAUSE_TIME:
              driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
      
          new_height = driver.execute_script("return document.body.scrollHeight")
          if new_height == last_height:
              break
          last_height = new_height
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-28
        • 2015-11-30
        • 2016-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多