【问题标题】:Can't collect links from website (Python)无法从网站收集链接(Python)
【发布时间】:2019-04-04 17:58:12
【问题描述】:

我正在用 Python 编写一个程序来收集网站的链接。代码是:

links = driver.find_elements_by_xpath('//*[@href]')
for link in links:
     print(link.get_attribute('href'))
time.sleep(1)

我在一些网站上试过,效果很好。问题是当我在特定站点(www.ifood.com.br)中使用时。它收集一些链接,然后返回一些错误。我是 Python 的初学者,所以我不知道它们是什么意思。拜托,我需要一些帮助。

代码结果:

https://d1jgln4w9al398.cloudfront.net/imagens/ce/wl/www.ifood.com.br/favicon.icohttps://d1jgln4w9al398.cloudfront.net/site/2.1.238-20181023.22/css/main.csshttps://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800https://www.ifood.com.br/

Traceback(最近一次调用最后):文件“C:\Users\jorda\Desktop\Python - Projetos\digitar ifood.py”,第 32 行,在 print(link.get_attribute('href')) 文件“C :\Users\jorda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py",第 143 行,在 get_attribute resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name}) 文件“C:\Users\jorda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py”,第 633 行,在_execute return self._parent.execute(command, params) File "C:\Users\jorda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py",第 321 行,在执行 self.error_handler.check_response(response) 文件“C:\Users\jorda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py” ,第 242 行,在 check_response 中引发 exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceExc eption:消息:过时的元素引用:元素未附加到页面文档(会话信息:chrome = 70.0.3538.77)(驱动程序信息:chromedriver = 2.42.591088(7b2b2dca23cca0862f674758c9a3933e685c27d5),平台=Windows NT 10.0.17134 x86_64

【问题讨论】:

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


    【解决方案1】:

    在你的错误日志中你可以看到

    selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

    通常,当您尝试与 DOM 中不再存在的 Web 元素进行交互时,就会发生这种情况。一个典型的场景可以描述为

    1. 您打开了一个网页。
    2. 找到一些元素并将它们保存到一个变量中。
    3. 页面 DOM 已更改(例如重新加载)。
    4. 您仍会看到相同的页面,但从 selenium 的角度来看,第 2 步中的元素已过时。

    因此,在您的情况下,您可以在调用 .findElements 之前尝试确保页面已完全加载(即不恢复 DOM)。 检查这是否能解决您的问题的最简单方法是在调用 .findElements 之前添加睡眠。

    time.sleep(5)
    links = driver.find_elements_by_xpath('//*[@href]')
    for link in links:
         print(link.get_attribute('href'))
    

    请注意,不建议使用 sleeps。因为例如,如果 5 秒有效,目前,不能保证在某些时候(由于连接不良)它不会破坏您的测试。相反,请使用智能等待条件,该条件将重复检查“页面加载”条件并仅在它发生时继续。更多细节可以在这里找到:Python Selenium stale element fix

    【讨论】:

    • 它就像一个魅力!感谢您的所有解释,这非常具有指导意义!现在我需要学习如何只打印我想要的链接,但这是另一段历史。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2013-12-20
    • 2018-05-06
    相关资源
    最近更新 更多