【问题标题】:Cannot scrape for infinite scrolling using Selenium无法使用 Selenium 进行无限滚动
【发布时间】:2019-07-05 23:03:00
【问题描述】:

过去 1 年我一直在使用 Selenium 抓取推文,但它无法将页面滚动到一个点之外并指向“返回顶部”。 如何使用 Selenium 解决这个问题?

这是我的代码-

driver=webdriver.Firefox(executable_path="/home/piyush/geckodriver")
url="https://twitter.com/narendramodi"
driver.get(url)
time.sleep(6)

lastHeight = driver.execute_script("return document.body.scrollHeight")
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(6)
    newHeight = driver.execute_script("return document.body.scrollHeight")
    if newHeight == lastHeight:
         break
    lastHeight = newHeight

这是作为图像的输出

【问题讨论】:

  • 我没有看到任何与报废相关的代码...
  • @DebanjanB 我没有附加抓取代码,因为我想摆脱这个“回到顶部”的问题。我可以抓取数据,但问题是页面在此之后不再滚动。
  • 这违反了 Twitter 服务条款。不允许刮擦。
  • @AndyPiper 但我现在可以使用 twitter 高级搜索选项抓取用户的所有推文。

标签: python selenium twitter web-scraping beautifulsoup


【解决方案1】:

您可以使用以下内容。尝试等待一段时间,直到“返回顶部”消失,然后继续抓取。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    disappeared = WebDriverWait(driver, 10).until(
        lambda x: not EC.visibility_of_element_located((By.ID, "myDynamicElement"))
    )

    if disappeared:
        print('Continue')
finally:
    driver.quit()

【讨论】:

  • 滚动的尝试在哪里?
  • @DebanjanB 问题不在于滚动
  • @DebanjanB 简而言之,我想到达页面底部,但它没有进入页面底部并显示“返回顶部”。我怎样才能让这个消失并加载更多推文?
  • @A.Albershteyn 它抛出错误为 "timeoutexception: message:" 。如何克服这个错误?
猜你喜欢
  • 2016-04-02
  • 2012-10-04
  • 1970-01-01
  • 2015-12-29
  • 2015-06-03
  • 2017-10-09
  • 2018-10-27
  • 2016-10-17
  • 1970-01-01
相关资源
最近更新 更多