Automated testing Python Selenium WebDriver

StaleElementReferenceException – what is it and how to fix it

This is a common mistake that can be found in unexpected places. Usually, you meet it like this: you find all the elements you need and save them into variables. Then, you start using the items you have saved. Some of them you click, in some you enter text. And now, at some point, when you try to click the next element, you get this error

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

What causes the StaleElementReferenceException

Selenium, when accessing the page, stores all the searched elements in its memory and assigns each of them its own internal id. You can see this id by creating an element and then getting its id:

button = driver.find_element(By.NAME, 'Button1')

You will see something like this:


When Selenium looses the element

When the page is reloaded, the element ceases to exist. And even if there is the same element on the page, it’s not the same element – it’s a new element that looks the same. Thus, if you found an element before the reload and saved it into a variable, then the variable stores a link to this element through the id assigned by Selenium. After reloading the page, this id becomes invalid. And if you try to perform any action with this element, you will get an error. In fact, this error says that such an element no longer exists.

Sometimes you may think that the page didn’t reload, but the StaleElementReferenceException still occurred. Try to observe everything that happens using the Developer Tools panel. Sometimes it happens that the page does not reload, but it is rerendered. In this case, Selenium’s association with the element is also lost and you see the same error.

Here is the the Selenium’s documentation about this exception.

How to fix it

To avoid this error, you need to search for this element again after reloading the page. Then Selenium will assign a new ID to this element and you can interact with it until the next page reload.

You can read about how to find elements using Python and Selenium in these posts:

By Eugene Okulik