我怎么能忽略Selenium中的异常呢?

2024-09-30 10:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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

但我有个例外

^{pr2}$

我也试过这个:

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

Tags: textbyokprodelementfindselectorcss
3条回答

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

在产生错误的代码段周围放置try except块。在

更具体地说约翰·戈登在说什么。处理^{}公共selenium异常并忽略它:

from selenium.common.exceptions import StaleElementReferenceException

try:
    element.click()
except StaleElementReferenceException:  # ignore this error
    pass  # TODO: consider logging the exception

相关问题 更多 >

    热门问题