Error: Stale Element Reference Exception
Error: Stale Element Reference Exception
When I was doing the project, I got this error “StaleElementReferenceException: stale element reference: element is not attached to the page document”.
Why I got this error when my locator is correct?
Sometimes it happens when we run, the xpath is not identified or not found in the DOM (Document Object Model)
What is Stale Element?
Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element.
What is the cause of this error?
The most common causes are:
The element has been deleted entirely. (most common cause)
The element is no longer attached to the DOM
How to overcome with this error?
Solution 1:
We can overcome this by refreshing the webpage
We can use the below one-line code
Eg: driver.navigate().refresh();
driver.findElement(By.xpath(" xpath ")).click();
Solution 2:
Using Try Catch Block
find the stale element exception and reidentify the same element with the same locator
and perform the same action in the catch block.
Eg:
Try{
driver.findElement(By.xpath(" xpath ")).click();
}
Catch( StaleElementReferenceException e)
{
// reidentify the same element with the same locator
driver.findElement(By.xpath(" xpath ")).click();
}
Solution 3:
Using ExpectedConditions.refreshed.
We can use Wait() till it gets identified
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" xpath ")));
We can also use ExpectedConditions.refreshed to avoid StaleElementReferenceException and retrieve the element again.
wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf(" xpath ")));
Solution 4:
Using POM
In POM,we use initElements() method which loads the elements but it won’t initialize elements.
initElements() takes latest address.
It initializes during the run time when we perform any action on the element. This process known as lazy initialization.