What is
StaleElementReferenceException:-
This exception occurs, when Selenium navigates to
a different page, come backs to the same old page and performs operations on
the old page. Technically, it occurs when the element defined in the Selenium
code is not found in the cache memory and the Selenium code is trying to locate
it .When we define an element on a page using
Selenium, Selenium stores it in a cache memory. The element stored in cache
memory generally gets deleted when the driver navigates away to another page
during Selenium code execution. On coming back to the same old page and then
trying to identify the cache removed element on the old page, we get
StaleElementReferenceException as a result.
Real time example with flow diagram
Common
Causes:-
1. The element has been deleted entirely.
2. The element is no longer attached to the DOM.
Sample Program to understand the error:-
Solution: - To
overcome Stale Element Reference Exception in Selenium
Solution 1:-
You can refresh the page and again try to for
same element.
Example: - If you are
trying to click on link and getting the exception then try in below format
Driver.navigate().refersh();
Solution 2:-
Sometimes it takes the time to attach element on
Dom so you can retry using for loop and try catch.
try{
Driver.findElement(By.id()).click();
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Solution 3:-
Wait for the element till it gets available
Use ExpectedConditions.refreshed to avoid
StaleElementReferenceException and retrieve the element again. This method
updates the element by redrawing it and we can access the referenced element.
Nice information
ReplyDeleteVery well explained Jitendra. This will help a lot.
ReplyDelete