陳舊元素引用

**陳舊元素引用** 錯誤是 WebDriver 錯誤,它發生是因為引用的 網頁元素 不再附加到 DOM

每個 DOM 元素在 WebDriver 中都由一個唯一的標識引用表示,稱為網頁元素。網頁元素引用是一個 UUID,用於執行針對特定元素的命令,例如 獲取元素的標籤名稱檢索元素的屬性

當某個元素不再附加到 DOM 時,例如它已從文件中刪除或文件已更改,則稱其為陳舊。例如,當您擁有網頁元素引用並且它獲取到的文件發生導航時,就會發生陳舊情況。

示例

文件導航

導航後,所有對先前文件的網頁元素引用將與文件一起被丟棄。這將導致任何後續與 網頁元素 的互動都失敗,並出現陳舊元素引用錯誤。

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 中移除時,其網頁元素引用將失效。這也會導致任何後續與 網頁元素 的互動都失敗,並出現陳舊元素引用錯誤。

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

另請參閱