python runtime_error ai_generated true

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

ID: python/pytest-selenium-stale-element

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-09-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.18 active — — —
4.20 active — — —

Root Cause

The test holds a WebElement reference obtained before a DOM re-render (navigation, AJAX update, React key change); the underlying node was replaced.

generic

中文

测试持有在 DOM 重新渲染(导航、AJAX 更新、React key 变化)之前获取的 WebElement 引用;底层节点已被替换。

Workarounds

  1. 90% success
    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')
  2. 93% success
    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()

Dead Ends

Common approaches that don't work:

  1. 75% fail

    The element may still be replaced after the sleep; timing is not the root cause and the test becomes slow and flaky.

  2. 85% fail

    Swallowing the exception skips the assertion entirely, producing false positives and hiding real UI regressions.