Avoid StaleElementReferenceException in Selenium



The StaleElementReferenceException is thrown if the webdriver makes an attempt to access a web element which is currently not available or invalid in DOM.

This can be due to refresh of the page or an element is accidentally deleted or modified or no longer connected to DOM. This type of exception can be avoided by following the below techniques −

  • Page refresh.

  • Having a retry mechanism.

  • Having a try-catch block.

  • Waiting for some expected criteria like presenceOfElementLocated or refreshing a page on getting a stale condition for an element.

Example

Code Implementation having StaleElementException

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class StaleElemntExc{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      // identify element
      WebElement n = driver.findElement(By.name("q"));
      n.sendKeys("tutorialspoint");
      //page refresh
      driver.navigate().refresh();
      n.sendKeys("Java");
      driver.close();
   }
}

Output

Code Implementation avoiding the StaleElementException.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.StaleElementReferenceException;
public class StaleElmntAvoid{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      // identify element
      WebElement n = driver.findElement(By.name("q"));
      n.sendKeys("tutorialspoint");
      //try-catch block
      try{
         n.sendKeys("Java");
      }
      catch(StaleElementReferenceException exp){
         n = driver.findElement(By.name("q"));
         n.sendKeys("Java");
         String v= n.getAttribute("value");
         System.out.println("Text is: " +v);
      }
      driver.close();
   }
}

Output

Updated on: 2021-04-06T11:27:24+05:30

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements