陈旧元素引用
元素引用已过期错误是 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