What is the StaleElementReferenceException in Selenium

49 views Asked by At

When I try to locate an element I am getting an error Like StaleElementReference

using WebDriver instance I try to do driver.findelement(By.xpath(Element)) it gives back staleelementreference exception.I am using selenium java

1

There are 1 answers

0
JeffC On

The StaleElementReferenceException is thrown when you try to access a stale element using element.getText(), element.click(), etc. A stale element is created when you store a reference to an element on the page then either the portion of the page that contains that element or the entire page changes/reloads. The end result is that the reference you hold in your variable is pointing at nothing. If you try to access it at that point, the exception is thrown.

A simple example of how to create a stale element,

// store a reference to an element
WebElement e = driver.findElement(By.id("id"));

// update the page by refreshing, creating the stale element
driver.navigate().refresh();

// accessing the stale element throws the exception
e.click();

The best way to avoid this issue is to be aware of and control the state of the page. If you perform an action that updates the page, make sure you refetch any variables that you stored before the page was refreshed.

To fix our simple example of a stale element,

// store a reference to an element
WebElement e = driver.findElement(By.id("id"));

// update the page by refreshing, creating the stale element
driver.navigate().refresh();

// refetch the element after the page refresh
e = driver.findElement(By.id("id"));

// accessing the stale element throws the exception
e.click();