- Stale Element means an old or no longer available element. We may face this exception when driver is trying to perform action on the Web element which is no longer exists or valid.
- There is a possibility that X path you have written is valid one, but web element is not visible (may be due to page refresh).
How Selenium locate a particular web element on the Web page ?
- In order to understand the StaleElementReferenceException, firstly we need to understand how Selenium locate a particular web element on the Web page ?
- Actually, when selenium web driver locates a particular web element on web page using DOM (Document Object Model), it uses a unique identifier Id to interact with the web element.
- While performing some operation on the web page, sometimes Ajax (Asynchronous JavaScript) components causes the part of web page to reload. This means that it is possible to update parts of a web page, without reloading the entire page.
- As a result of Ajax components, part of web page got refreshed and its DOM also got rebuild. It also changes the unique identifier ID associated with the web element under this Ajax component.
- Now, when selenium tries to interact with web element, StaleElementReferenceException will thrown because it uses the old identifier id to perform the operation.
Handle StaleElementReferenceException:
- Enclose the test throwing Exception in try/catch block. After catching the StaleElementReferenceException in catch block, use the driver.findElement(write locator here) method again to locate the same web element and perform the required operation.
- We will be able to interact with the element now because selenium will use the new identifier Id now to interact with the same web element.
@Test
public void StaleElementExceptionMethod() {
try {
// this method will throw StaleElement exception
driver.findElement(locator).click();
} catch (StaleElementReferenceException e) {
driver.findElement(locator).click();
}
}