HomeScienceTechnologyHow to handle StaleElementReferenceException in Selenium Webdriver Example

How to handle StaleElementReferenceException 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”)));

mm
Pratibha Ramteke
10+ years of experience As Software Development Engineer in Test (SDET) having proven track record in leading automation and quality teams of enterprise class products for growing organizations.  Presently involved in Automation, DevOps and Performance verticals for enterprise class product’s testing.  Expert in Automation based out of API and UI testing
RELATED ARTICLES
- Advertisment -

Most Popular

Translate »