Close announcement
Back to blog

How to Handle StaleElementReferenceException in Selenium

StaleElementReferenceException how to handle

Selenium is a powerful tool for automating web applications for testing purposes. However, while using Selenium, you may encounter various exceptions, and one of the most common ones is the StaleElementReferenceException. When working with Selenium WebDriver in Java, encountering a StaleElementReferenceException is a common issue that test automation engineers face. This exception indicates that the web element being referenced is no longer attached to the DOM of the page. This typically occurs when the element has been removed from the DOM, the page where the element resides has been refreshed, or the element is temporarily unavailable due to a JavaScript operation. To handle this, it is crucial to find the element again before interacting with it. Using explicit waits can ensure the WebDriver waits for the element to be available, present, and visible before any action is performed. Additionally, wrapping interactions within a try-catch block and updating the reference of the web element each time can help avoid the occurrence of StaleElementReferenceException. By implementing these strategies, you can effectively handle the stale element reference exception in Selenium WebDriver, ensuring robust and reliable test execution.

Understanding StaleElementReferenceException

The staleelementreferenceexception indicates that the element you are trying to interact with is no longer valid. This can happen for several reasons:

  1. The DOM has been refreshed: If the web page is reloaded or a portion of the DOM is updated via JavaScript, the reference to the element you previously located becomes stale.
  2. Navigation: Moving to a different page and then attempting to access elements from the previous page.
  3. Element removed or replaced: JavaScript or AJAX calls may dynamically modify the DOM, removing or replacing the element you are referencing.

Check also our guide on how to set up Regression Testing with BugBug.

Identifying StaleElementReferenceException

When the exception occurs, it typically looks like this:

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

This message clearly indicates that the element reference is no longer valid, and you need to re-locate the element.

Strategies to Handle Stale Element Reference Exception

Here are some effective strategies to handle this exception:

1. Re-locate the Element

The simplest way to handle this exception is to re-locate the element just before interacting with it. This ensures that you have the latest reference to the element.

WebElement element = driver.findElement(By.id("example"));
element.click();

2. Use Explicit Waits

Explicit waits can be used to wait for certain conditions to be met before proceeding with actions. This is particularly useful when dealing with dynamic web pages.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("example")));
element.click();

3. Try-Catch Block with Retry Logic

Implementing a retry mechanism within a try-catch block can help in scenarios where the DOM changes frequently.

public void clickElement(By locator) {
   int attempts = 0;
   while (attempts < 2) {
       try {
           WebElement element = driver.findElement(locator);
           element.click();
           break;
       } catch (StaleElementReferenceException e) {
           attempts++;
       }
   }
}

4. Avoiding Unnecessary DOM Interactions

Reduce interactions with the DOM whenever possible. For example, minimize the number of times you locate elements and perform actions on them only when necessary.

5. Wait for Page to Load Completely

Ensure the page has fully loaded before performing any actions. This can be achieved using JavaScript.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.readyState").equals("complete");

6. Using ExpectedConditions for Stability

ExpectedConditions in Selenium provide various conditions to wait for specific states of elements. Utilizing these conditions can help manage the state of elements more effectively.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf(element)));
element = driver.findElement(By.id("example"));
element.click();

Detailed Example: Handling Stale Element Reference Exception in a Selenium Test

Let's dive deeper into a practical example. Consider a Selenium test where you need to click a button that refreshes a section of the web page, causing the element references to become stale.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class StaleElementExample {
   WebDriver driver;
   public StaleElementExample(WebDriver driver) {
       this.driver = driver;
   }
   public void clickButton() {
       try {
           WebElement button = driver.findElement(By.id("refreshButton"));
           button.click(); // Simulate waiting for the page to refresh
           WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
           wait.until(ExpectedConditions.stalenessOf(button)); // Re-locate the button after refresh
           button = driver.findElement(By.id("refreshButton"));
           button.click();
       } catch (StaleElementReferenceException e) { // Handle exception WebElement
           button = driver.findElement(By.id("refreshButton"));
           button.click();
       }
   }
   public static void main(String[] args) {
       // Initialize WebDriver (e.g., ChromeDriver)
       WebDriver driver = new ChromeDriver();
       driver.get("http://example.com");
       StaleElementExample example = new StaleElementExample(driver);
       example.clickButton();
       driver.quit();
   }
}

Handling StaleElementReferenceException in Selenium - Final Thoughts

Handling Stale Element Reference Exception in Selenium requires a good understanding of how web pages work and how elements within the DOM can change over time. By implementing strategies like re-locating elements, using explicit waits, retry mechanisms, and ensuring the page is fully loaded, you can effectively manage and overcome this exception. These practices will make your Selenium scripts more robust and reliable.

Remember, the key is to ensure that you always have the latest reference to the element you are interacting with.

Happy (automated) testing!

Speed up the entire testing process now

Automate web app testing easier than ever. Without excessive costs. Faster than coding. Free forever.

Dominik Szahidewicz

Software Developer

Application Consultant working as a Tech Writer https://www.linkedin.com/in/dominikdurejko/

Don't miss any updates
Get more tips and product related content. Zero spam.