StaleElementReferenceException is one of the most intriguing exceptions that you would have experienced in your selenium tests. Hope this post can help you resolve this exception from reoccurring in your tests.
What is StaleElementReferenceException?
Per Selenium Webdriver documentation, the reference to an element is now “stale” — the element no longer appears on the DOM of the page. Simply put, the element you located using the findElement method disappeared when you started interacting with it.
Let us understand some insights about how Selenium WebDriver handles this scenario:
When you write the syntax to perform an action using Selenium WebDriver; it internally calls the WebDriver API associated with that method.
Way of Working — Selenium WebDriver
For example, if you like to look up an element in the browser using Selenium WebDriver in Java, the syntax looks following:
Locate an Element using Id as Selector
Now, the java method internally calls the WebDriver API — the post request through passing the locator information in the body like below:
FindElement request posted through PostMan
In the above request, localhost points to chrome driver running as a local server in port 9515.
Note: When running your tests from your IDE like eclipse, Selenium finds the free port at runtime and that may not be the 9515, which is the default port.
The API response from the chrome driver server on a successful match will return the WebElement, and the response will be like the below:Response with Element Information
Here, you will find the element information with a unique identifier for every session for that requested DOM. Note: The element information will differ when the page is reloaded or navigated from different sessions.