Handling StaleElementReferenceException in Selenium Java - Build an Automation Script
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.
Now add data-driven testing to click multiple buttons with different ids and handle stale elements for each