Skip to main content

Command Palette

Search for a command to run...

How To Overcome StaleElementReferenceException in Selenium?

Published
2 min read
How To Overcome StaleElementReferenceException in Selenium?
G

Results-driven SDET with expertise in automation frameworks, API testing, and CI/CD pipelines. Proficient in Selenium, Appium, Postman, JUnit, TestNG and Jenkins. Skilled in Java and performance testing, ensuring high-quality software delivery in Agile environments.

The StaleElementReferenceException in Selenium occurs when an element that was found in the DOM becomes stale or invalid (often due to a page refresh, navigation, or DOM update). Here's how to handle and overcome this exception effectively:

Solutions to Overcome StaleElementReferenceException

1. Use WebDriverWait with Expected Conditions

Wait until the element becomes visible or clickable before interacting with it.

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

2. Refetch the Element

Locate the element again when required instead of holding its reference.

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

3. Try-Catch Block

Handle the exception by reattempting the interaction.

javaCopyEditWebElement element = null;
for (int i = 0; i < 3; i++) {
    try {
        element = driver.findElement(By.id("elementId"));
        element.click();
        break;
    } catch (StaleElementReferenceException e) {
        System.out.println("Stale element, retrying...");
    }
}

4. Use ExpectedConditions.refreshed()

Ensure the element is refreshed and valid before interacting with it.

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

5. Avoid Premature Page Actions

Ensure the page has fully loaded before interacting with elements. You can wait for the presence of specific elements.

javaCopyEditnew WebDriverWait(driver, Duration.ofSeconds(10))
    .until(ExpectedConditions.presenceOfElementLocated(By.id("elementId")));

6. Scroll to Element (If Needed)

Sometimes scrolling the element into view helps.

javaCopyEditJavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].scrollIntoView(true);", element);
element.click();

More from this blog

SDET insider

11 posts