如何忽略 Selenium 中的异常?
How can I ignore the exception in Selenium?
我使用 Python Selenium 抓取网站,
但是我的爬虫因为异常停止了:
StaleElementReferenceException
: Message: stale element reference: element is not attached 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 块。
更具体地说明 John Gordon 所说的内容。处理 StaleElementReferenceException
常见的 selenium 异常并忽略它:
from selenium.common.exceptions import StaleElementReferenceException
try:
element.click()
except StaleElementReferenceException: # ignore this error
pass # TODO: consider logging the exception
浏览器渲染引擎或 Javascript 引擎似乎正在使用该元素,并且正在阻止对该元素的其他外部操作。您可以在一段时间后尝试访问它。如果它在较长时间内不可访问,则可以抛出异常。给出了一些很好的例子 here.
我使用 Python Selenium 抓取网站, 但是我的爬虫因为异常停止了:
StaleElementReferenceException
: Message: stale element reference: element is not attached 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 块。
更具体地说明 John Gordon 所说的内容。处理 StaleElementReferenceException
常见的 selenium 异常并忽略它:
from selenium.common.exceptions import StaleElementReferenceException
try:
element.click()
except StaleElementReferenceException: # ignore this error
pass # TODO: consider logging the exception
浏览器渲染引擎或 Javascript 引擎似乎正在使用该元素,并且正在阻止对该元素的其他外部操作。您可以在一段时间后尝试访问它。如果它在较长时间内不可访问,则可以抛出异常。给出了一些很好的例子 here.