About this lesson
Fix StaleElementReferenceException in Selenium Python by finding the element again
Selenium Python AssignmentsAdvancedJavaScript
How it works
A WebElement is not the page content. It is a handle holding an internal id for one node of the current document. A reload throws that node away and builds a new document, so the id points at nothing. Python does not notice until you use the object.
Using it raises StaleElementReferenceException with the message "stale element reference: stale element not found". After a refresh, every call I tried raised it, from text to click. Retrying the old object cannot work. Run find_element again for a new handle. The old and new objects compared False with ==, though they describe the same field.
Python catches it with try and except, using the class imported from selenium.common.exceptions. Catch that class only. A bare except also swallows real failures.
About the assignment
You cause the error on purpose: use an element from before a reload, record that it failed, find the field again, and read its value.
What you will do
- Find the pre-filled field, store it, then reload the page.
- In a
tryblock, call something simple on the old element, catch the exception in anexceptclause, and print which outcome happened. - After the
tryblock, find the field again. - Print its value attribute on the second line.
Common mistakes
Catching the wrong exception
except NoSuchElementExceptiondoes not help. The traceback still ends withStaleElementReferenceException, a different class.Re-using the old variable name for the old object
Calling
get_attributeon the first variable after the refresh raises again. Use the newfind_elementresult.Using a bare except
It catches real locator errors too, so the test reports success for a page it never looked at.
In a real test suite
Page objects avoid the problem by storing locators, not elements, so each method finds a fresh handle. Some teams add a retry helper that catches this one exception and repeats the lookup.
The next lessons cover screenshots, a good way to see what the page held when something went wrong.
Related lessons
- Go Back and ForwardBack and forward swap documents too, so a handle fails while its page is away, though it may work on return.
- Fix a Locator That Does Not ExistAnother exception lesson, this time for a locator that matches nothing.
- Diagnose a Wait That Times OutDiagnose waits that fail with an exception, a similar habit.
To try one of these calls on any page without a task, open the Online Selenium Python Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException
driver = webdriver.Chrome()
try:
driver.get("https://testkru.com/Elements/TextFields")
# Refresh, catch the stale element, then read the value again
finally:
driver.quit()