Selenium WebDriver StaleElementReferenceException.

SeleniumAutomation TestingTesting Tools

We have StaleElementReferenceException in Selenium webdriver. As the name suggests, the word stale refers to something which is not new and perished. There may be a scenario in which an element which was present in DOM previously is now no longer available due to modification in DOM.

In such a condition, if we try to access that element then StaleElementReferenceException is thrown. This type of exception is encountered due to the below reasons −

  • The element is not present in the DOM any more.

  • The element has been removed totally.

There are certain ways we can prevent a StaleElementReferenceException as described below −

We can reload the webpage and try to interact with the same element.

driver.navigate().refresh();
driver.findElement(By.id("txt")).sendKeys("Selenium");

We can add a try catch block and interact with the same element. Here with for loop, there shall be five attempts. If the element is identified before the five attempts, there shall be exit from the loop.

for(int k=0; k<=5;k++){
   try{
      driver.findElement(By.id("txt")).sendKeys("Selenium");
      break;
   }
   catch(Exception exp){
      System.out.println(exp.message());
   }
}

To prevent a StaleElementReferenceException we can add the explicit wait [synchronization] to wait for the element till the element is rendered in DOM with the help of the expected condition presenceOfElementLocated.

w.until(ExpectedConditions.presenceOfElementLocated(By.name("presence")));
raja
Published on 26-Oct-2020 11:31:29
Advertisements