【问题标题】:can selenium scroll down browser and only parse new content at the same time?selenium 可以向下滚动浏览器并同时只解析新内容吗?
【发布时间】:2015-01-05 10:13:04
【问题描述】:

我要解析的网页有几千个链接。它还具有无限滚动功能,这意味着我需要在 Selenium 中使用 send_keys( Keys.PAGE_DOWN ) 来扩展页面以获取更多内容。

是否可以使用 selenium 向下滚动浏览器同时只解析新内容?我不想重复解析旧的内容或等待网页到达底部再解析,因为网页有大量的链接。

有什么建议吗?如果有更好的 python 库可以帮助我做到这一点,也请告诉我。谢谢。

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    您可以编写一个简单的循环,使用 xpath 仅提取新呈现的链接。在不了解您正在解析的页面的更多信息的情况下,我会假设所有 a 标记都是公平的游戏:

    driver = webdriver.Firefox()
    links = []
    
    while True:
        # Get any links beyond the ones we already have
        elements = driver.find_elements_by_xpath(
            "//a[position()>{}]".format(len(links))
    
        # If there are no more links, stop
        if not len(elements):
            break
    
        # "Parse" the links
        links += elements
    
        # Page down to trigger load of next batch
        driver.find_element_by_tag_name("html").send_keys(Keys.PAGE_DOWN)
    

    【讨论】:

      猜你喜欢
      • 2013-08-24
      • 2017-08-27
      • 2017-07-07
      • 1970-01-01
      • 2018-01-15
      • 2014-12-19
      • 2018-08-31
      • 2014-12-11
      • 2019-09-22
      相关资源
      最近更新 更多