Stale element reference
Thestale element reference error is aWebDriver error that occurs because the referencedweb element is no longer attached to theDOM.
Every DOM element is represented in WebDriver by a unique identifying reference, known as aweb element.The web element reference is aUUID used to execute commands targeting specific elements, such asgetting an element's tag name andretrieving a property off an element.
When an element is no longer attached to the DOM, i.e., it has been removed from the document or the document has changed, it is said to bestale. Staleness occurs for example when you have a web element reference and the document it was retrieved from navigates.
In this article
Examples
>Document navigation
Upon navigation, all web element references to the previous document will be discarded along with the document. This will cause any subsequent interaction with theweb element to fail with the stale element reference error:
import urllibfrom selenium import webdriverfrom selenium.common import exceptionsdef 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_nameexcept exceptions.StaleElementReferenceException as e: print(e)
Output:
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
Node removal
When a document node is removed from the DOM, its web element reference will be invalidated. This will also cause any subsequent interaction with theweb element to fail with the stale element reference error:
import urllibfrom selenium import webdriverfrom selenium.common import exceptionsdef 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)
Output:
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