Stale means old, decayed, no longer fresh. 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. If the DOM changes then the WebElement goes stale. If we try
to interact with an element which is staled then the StaleElementReferenceException is thrown.
What are the Causes of StaleElement Exception
We face this stale element reference exception when the element we are interacting with is destroyed
and then recreated again. When this happens the reference of the element in the DOM becomes stale.
Hence we are not able to get the reference to the element.
Cause 1: The referenced web element has been deleted completely.
Cause 2: The referenced element is no longer attached to the DOM
How To Overcome Stale Element Reference Exception in Selenium:
Solution 1: Refreshing the web page
driver.navigate().refersh();
driver.findElement(By.xpath("xpath here")).click();
Solution 2: Using Try Catch Block
for(int i=0; i<=2;i++){
try{
driver.findElement(By.xpath("xpath here")).click();
break;
}
catch(Exception e){
Sysout(e.getMessage());
}
}
Solution 3: Using ExpectedConditions.refreshed
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("table")));
Solution 4: Using POM
We could avoid StaleElementException using POM. In POM, we use initElements() method which
loads the element but it won’t initialize elements. initElements()
takes latest address. It initializes during run time when we try to
perform any action on an element. This process is also known as Lazy Initialization.