Resolve Stale Element Reference Exception in Selenium WebDriver
We can resolve StaleElementReferenceException in Selenium webdriver. The term stale means something which is not fresh and decayed. Thus a stale element points to an element which is not present any more.
There may be a case, when an element was in DOM initially but after modifications in Document Object Model (DOM), the element becomes stale and the StaleElementReferenceException is thrown if we make an attempt to access this element.
This exception is caused whenever an element is not present in the DOM, or deleted. We can handle this exception by the following ways −
Refreshing the page and verifying again.
Implement retry method.
Example
Code Implementation to illustrate 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 StaleElmnt{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement l = driver.findElement(By.id("gsc−i−id1")); l.sendKeys("Selenium"); //refresh page driver.navigate().refresh(); l.sendKeys("Selenium"); driver.quit(); } }
Output
Example
Code Implementation to fix 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 StaleElmntFix{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement l = driver.findElement(By.id("gsc−i−id1")); l.sendKeys("Selenium"); //refresh page driver.navigate().refresh(); //fix exception with try−catch block try{ l.sendKeys("Selenium"); } catch(StaleElementReferenceException e){ l = driver.findElement(By.id("gsc−i−id1")); l.sendKeys("Selenium"); //obtain value entered String s= l.getAttribute("value"); System.out.println("Value entered is: " +s); } driver.quit(); } }
Output
Advertisements