【问题标题】:My scraper throws an error instead of continuing on我的刮刀抛出错误而不是继续
【发布时间】:2018-07-13 12:19:02
【问题描述】:

我在 python 中结合 selenium 创建了一个刮板,用于从网站收集一些信息。但是,我面临的问题是在收集单个潜在客户后,刮板会抛出错误element is not attached to the page document。

考虑以下代码:

  1. for loop 滚动的名称有 20 个,并且刮板应该点击每个名称。

  2. 点击名字后,它会在新页面中等待文档可用。

  3. 在该页面的右上角有一个显示更多按钮,单击该按钮可解开隐藏的信息。 (它仍然停留在第二页,只是显示了一个新信息)。

  4. 一旦信息显示,scraper 就会成功收集。

  5. 然后它应该返回到循环开始的起始页面并点击下一个名称。但是,它不会单击下一个名称,而是会引发以下错误(在link.click() 行上)。

我试图通过使用wait.until(EC.staleness_of(item)) 来消除陈旧元素错误,但它不起作用。

for link in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"div.presence-entity__image"))):
    link.click() #error thrown here
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button[data-control-name='contact_see_more']"))).click()
    item = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,".pv-contact-info__ci-container a[href^='mailto:']")))
    print(item.get_attribute("href"))
    driver.execute_script("window.history.go(-1)")
    wait.until(EC.staleness_of(item))

我遇到的错误:

line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

我试图描绘正在发生的事情。对此的任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver web-scraping


    【解决方案1】:

    您最好收集所有链接并循环导航到所有这些链接,而不是点击循环中的每个链接:

    links = [link.get_attribute('href') for link in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"a.mn-person-info__picture.ember-view")))]
    for link in links:
        driver.get(link)
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button[data-control-name='contact_see_more']"))).click()
        item = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,".pv-contact-info__ci-container a[href^='mailto:']")))
        print(item.get_attribute("href"))
    

    请注意,要获取所有链接,您可能需要向下滚动连接页面以通过 XHR 加载更多连接

    【讨论】:

    • 你的解决方案怎么能一直如此完美@安德森爵士?它做到了,就像我从未想象过的那样。我删除了我的评论以确保这篇文章的安全。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2017-03-24
    • 2016-02-24
    • 2018-12-23
    相关资源
    最近更新 更多