0 votes
1 view
in Devops and Agile by (19.8k points)

I get this error when running my tests: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM

Any idea on how to solve the above exception? This happens in Selenium Grid which has a ref Xpath expression which is dynamic

1 Answer

0 votes
by (63.4k points)

Solution 1:

You could refresh the page and check out once more for the same element.

Assume you're attempting to click on a link and obtaining the stale element exception.

Sample code to overcome the issue

driver.navigate().refersh();

driver.findElement(By.xpath("xpath here")).click();

Solution 2:

If an element is not attached to DOM then you could try using ‘try-catch block’ within ‘for loop’

// using for loop, it tries for three times.

// If the element is found for the first time then it breaks from the for loop and comes out of the loop

for(int i=0; i<=2;i++){

  try{

     driver.findElement(By.xpath("xpath here")).click();

     break;

  }

  catch(Exception e){

     System.out(e.getMessage());

  }

}

Solution 3:

Wait for the element till it 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.

.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf("table")));

I hope this helps!

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...