python
runtime_error
ai_generated
true
selenium.common.exceptions.StaleElementReferenceException: 消息: 陈旧元素引用: 元素未附加到页面文档
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
ID: python/pytest-selenium-stale-element
80%修复率
86%置信度
0证据数
2024-09-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 4.18 | active | — | — | — |
| 4.20 | active | — | — | — |
根因分析
测试持有在 DOM 重新渲染(导航、AJAX 更新、React key 变化)之前获取的 WebElement 引用;底层节点已被替换。
English
The test holds a WebElement reference obtained before a DOM re-render (navigation, AJAX update, React key change); the underlying node was replaced.
解决方案
-
90% 成功率
def click_row(driver, row_text): for _ in range(5): try: row = driver.find_element(By.XPATH, f"//tr[td[text()='{row_text}']]") row.find_element(By.CSS_SELECTOR, 'button.delete').click() return except StaleElementReferenceException: continue raise AssertionError('element never stabilized') -
93% 成功率
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By el = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, 'submit')) ) el.click()
无效尝试
常见但无效的做法:
-
75% 失败
The element may still be replaced after the sleep; timing is not the root cause and the test becomes slow and flaky.
-
85% 失败
Swallowing the exception skips the assertion entirely, producing false positives and hiding real UI regressions.