【问题标题】:How can I ignore the exception in Selenium?如何忽略 Selenium 中的异常?
【发布时间】:2016-11-01 13:54:26
【问题描述】:

我使用 Python Selenium 来抓取网站, 但是我的爬虫因为异常停止了:

StaleElementReferenceException: Message: stale element reference: element is not attach to the page document

即使没有附加元素,我如何继续抓取?

更新

我将代码更改为:

try:
    libelle1 = prod.find_element_by_css_selector('.em11')
    libelle1produit = libelle1.text  # libelle1 OK
    libelle1produit = libelle1produit.decode('utf-8', 'strict')
except StaleElementReferenceException:
    pass

但我有这个例外

NoSuchElementException: Message: no such element

我也试过这个:

try:
    libelle1 = prod.find_element_by_css_selector('.em11')
    libelle1produit = libelle1.text  # libelle1 OK
    libelle1produit = libelle1produit.decode('utf-8', 'strict')
except :
    pass

【问题讨论】:

  • 考虑发布更多导致问题的代码。否则,下一个最好的方法就是使用 try-except 或 with supress 上下文管理器忽略异常

标签: python selenium selenium-webdriver web-scraping web-crawler


【解决方案1】:

在产生该错误的代码周围放置一个 try-except 块。

【讨论】:

    【解决方案2】:

    更具体地说明约翰·戈登在说什么。处理StaleElementReferenceException common selenium 异常并忽略它:

    from selenium.common.exceptions import StaleElementReferenceException
    
    try:
        element.click()
    except StaleElementReferenceException:  # ignore this error
        pass  # TODO: consider logging the exception
    

    【讨论】:

      【解决方案3】:

      看起来浏览器渲染引擎或 Javascript 引擎正在使用该元素,并且正在阻止对该元素的其他外部操作。您可以在一段时间后尝试访问它。如果在较长时间内无法访问它,则可能会引发异常。 here 给出了一些很好的例子。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-13
        • 1970-01-01
        • 1970-01-01
        • 2014-01-05
        • 2020-03-05
        相关资源
        最近更新 更多