0
0
Selenium Javatesting~15 mins

Handling StaleElementReferenceException in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Handle StaleElementReferenceException when clicking a dynamic button
Preconditions (2)
Step 1: Navigate to the test page URL
Step 2: Locate the button with id 'dynamic-button'
Step 3: Click the button
Step 4: Immediately try to click the same button again
Step 5: If StaleElementReferenceException occurs, re-locate the button and click it again
✅ Expected Result: The button is clicked twice successfully without test failure due to StaleElementReferenceException
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify no StaleElementReferenceException is thrown during the second click
Verify the button click triggers expected page behavior (e.g., URL change or element update)
Best Practices:
Use explicit waits to wait for element to be clickable
Catch StaleElementReferenceException and re-locate the element before retrying
Avoid storing WebElement references for long periods when page updates dynamically
Automated Solution
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class HandleStaleElement {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        try {
            driver.get("https://example.com/testpage");

            // Locate the button
            WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("dynamic-button")));

            // First click
            button.click();

            // Try second click, handle stale element
            try {
                button.click();
            } catch (StaleElementReferenceException e) {
                // Re-locate the button and click again
                button = wait.until(ExpectedConditions.elementToBeClickable(By.id("dynamic-button")));
                button.click();
            }

            // Add assertion or verification here if needed
            // For example, check URL or element text changed
            String currentUrl = driver.getCurrentUrl();
            if (!currentUrl.contains("expected-part-after-click")) {
                throw new AssertionError("URL did not change as expected after button clicks");
            }

            System.out.println("Test passed: Button clicked twice without stale element error.");

        } finally {
            driver.quit();
        }
    }
}

This code uses Selenium WebDriver with Java to automate the test case.

First, it opens the browser and navigates to the test page.

It waits explicitly for the button with id 'dynamic-button' to be clickable, then clicks it once.

For the second click, it tries to click the same WebElement. If a StaleElementReferenceException occurs, it catches the exception, re-locates the button again using the explicit wait, and clicks it again.

This approach ensures the test does not fail due to stale element references caused by page updates.

Finally, it verifies the URL changed as expected after the clicks to confirm the button worked.

The driver quits to close the browser.

Common Mistakes - 3 Pitfalls
Storing WebElement in a variable and reusing it after page update without re-locating
Not using explicit waits and trying to interact immediately
Ignoring StaleElementReferenceException and letting test fail
Bonus Challenge

Now add data-driven testing to click multiple buttons with different ids and handle stale elements for each

Show Hint