陳舊元素引用
元素引用已過期錯誤是 WebDriver 錯誤,發生的原因是引用的 Web 元素 不再附加到 DOM。
WebDriver 中的每個 DOM 元素都由一個唯一的識別符號引用表示,稱為 Web 元素。Web 元素引用是一個 UUID,用於執行針對特定元素的命令,例如 獲取元素的標籤名 和 檢索元素的屬性。
當一個元素不再附加到 DOM 時,也就是說,當它已被從文件中移除或文件已更改時,它就被認為是已過期。例如,當你有一個 Web 元素引用,而它所屬的文件已導航到其他頁面時,就會發生過期。
示例
文件導航
導航後,先前文件的所有 Web 元素引用都將與文件一起被丟棄。這會導致後續對 Web 元素 的任何互動都因元素引用已過期錯誤而失敗。
python
import urllib
from selenium import webdriver
from selenium.common import exceptions
def inline(doc):
return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))
session = webdriver.Firefox()
session.get(inline("<strong>foo</strong>"))
foo = session.find_element_by_css_selector("strong")
session.get(inline("<i>bar</i>"))
try:
foo.tag_name
except exceptions.StaleElementReferenceException as e:
print(e)
輸出
StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
節點移除
當文件節點從 DOM 中移除時,其 Web 元素引用將失效。這同樣會導致後續對 Web 元素 的任何互動都因元素引用已過期錯誤而失敗。
python
import urllib
from selenium import webdriver
from selenium.common import exceptions
def inline(doc):
return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))
session = webdriver.Firefox()
session.get(inline("<button>foo</button>"))
button = session.find_element_by_css_selector("button")
session.execute_script("""
let [button] = arguments;
button.remove();
""", script_args=(button,))
try:
button.click()
except exceptions.StaleElementReferenceException as e:
print(e)
輸出
StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed