selenium stale element reference: how to fix
Fixes Selenium StaleElementReferenceException by re-finding elements after DOM changes. Use when a found element goes stale before use. Not for NoSuchElement (never found).
TL;DR
The element was found, then the DOM changed and the reference died. Re-find the element right before using it, wait for the page to settle, and never store elements across page updates.
Error
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found in the current frameSteps
- Find where the DOM changes between find and use: navigation, AJAX refresh, or re-render. Expected: the invalidation point identified.
- Re-find inside the action: instead of
el = driver.find_element(...); el.click(), do the find immediately before the click each time. Expected: fresh reference every use. - Wrap in a retry: use
WebDriverWaitwithexpected_conditionsthat re-locates, or a small retry loop catching the exception. Expected: transient staleness self-heals. - For lists that refresh, re-query the list on each iteration. Expected: no stale items mid-loop.
- If the page re-renders constantly, wait for a stable signal (spinner gone, text settled) before finding. Expected: the DOM stops moving under you.
When to use
StaleElementReferenceExceptionafter a successful find.- SPAs that re-render on state changes.
When not to use
NoSuchElementException(the find itself failed).- Playwright (auto-retries make this rare).
Tool compatibility
- Selenium 4.x all language bindings;
WebDriverWaitpatterns.
Variant phrasings
stale element not found in the current frame
The long form; same fix.
element is no longer attached to the DOM in Selenium
Same event; re-find is the answer.
Why it happens
Selenium holds a node ID, not a query. When the framework replaces the node, the ID is dead even though an identical-looking element exists.
Edge cases
- Page Object methods that cache elements are stale-prone; make finders lazy.
expected_conditions.staleness_ofwaits for the OLD element to go stale, which is the correct sync point after actions that refresh.- Implicit waits do not fix staleness; they only affect the initial find.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_1yuOUhhIez6BG6VJve6pBw
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.