In this post we will see how to handle how to handle stale element reference exception. First of all we should understand what is stale element –
Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver.
Possible causes for an stale element exception-
1 -The element has been deleted entirely.
2- The element is no longer attached to the DOM.
How to fix or handle it
Most easy easy out to handle this is to refresh the page, On refreshing it, most of the time driver found the element, But its not the perfect solution-
The second option you can try is to place your driver interaction command inside some loop and to repeating that for a couple of times, 2-3 times, refer below code.
System.out.println("Exception-Element not found");
however this method is also but hardcoded and not generic, it can also fail, if even after 3 attempt element is not found however its best to use third option which is placing Do-While loop .
Use a do-While loop on an element which is causing stale element exception-Initialize a counter with Zero and iterate and identify webelement, once its enabled and displayed perform action and exit from loop.
String str ;
if(driver.findelement(By.id()).isenabled() && driver.findelement(By.id()).isdisplayed() )
while(Counter == 0)
Using a do-while loop is most generic and perfect solution for such stale element exceptions, it sould be able to find element even if it appear a bit late after loading a web page.