HomeScienceTechnologyHow to handle StaleElement Reference Exception in Selenium Webdriver Example

How to handle StaleElement Reference Exception in Selenium Webdriver Example

A stale element reference exception is thrown in one of two cases, the first being more common than the second:

  • The element has been deleted entirely.
  • The element is no longer attached to the DOM.

Example:


@Test

public void getData(){
    Try{
    WebElement table = findElementById("table");
    List<WebElement> allRows = table.findElements(By.tagName("tr"));
    for (WebElement row : allRows)
        {
            List<WebElement> cells = row.findElements(By.tagName("td"));
            for (WebElement cell : cells)
            {
                WebElement listName = cell.findElement(By.xpath
                  ("./* [text()='data_']"));
                listName.click();
            }
        }
    }catch(Exception exception){
      System.out.println(“Exception:” + exception.toString());
    }
}

Problem:


On executing above test, stateElementReferenceExpection occurred while fetching the rows from the table
Cause:


This caused due to the 2nd point mentioned above. The element is no longer attached to the DOM.
Reason:


This exception is thrown when the element we are interacting 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 of the element.
Solution:


Wait for the element till its gets available
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“table”)))

  • 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.

wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf(“table”)));

RELATED ARTICLES
- Advertisment -

Most Popular

Translate »