如何忽略 Selenium 中的异常?

par*_*rik 2 python selenium web-crawler web-scraping selenium-webdriver

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

StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面文档

即使元素未附加,我如何继续爬行?

更新

我将我的代码更改为:

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

但我有这个例外

NoSuchElementException: Message: no such element
Run Code Online (Sandbox Code Playgroud)

我也尝试过这个:

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

Joh*_*don 5

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


ale*_*cxe 5

更具体地了解约翰·戈登正在谈论的内容。处理StaleElementReferenceException常见的selenium异常并忽略它:

from selenium.common.exceptions import StaleElementReferenceException

try:
    element.click()
except StaleElementReferenceException:  # ignore this error
    pass  # TODO: consider logging the exception
Run Code Online (Sandbox Code Playgroud)