0

我用Python的硒刮網站, 但我履帶停止,因爲一個例外:如何忽略Selenium中的異常?

StaleElementReferenceException:消息:過時的元素參考:元素沒有被附加到頁面文件

即使未連接元素,我如何繼續爬行?

UPDATE

我我的代碼更改爲:

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 
+3

考慮發佈一些導致問題的代碼。否則,提供的下一個最好的事情就是簡單地用try-except或者with with supress' context manager來忽略異常 – sytech

回答

1

它看起來像瀏覽器渲染引擎或JavaScript引擎使用元素,它是阻斷這種元素其他外部操作。您可以嘗試在一段時間後訪問它。如果持續時間較長,則可能會引發異常。一些很好的例子給出here

3

在產生該錯誤的代碼塊周圍放置try-except塊。

3

更具體地說明約翰戈登談論的是什麼。處理StaleElementReferenceException共同硒異常,忽略它:

from selenium.common.exceptions import StaleElementReferenceException 

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