Home >Java >javaTutorial >How to Resolve the Stale Element Reference Exception in Selenium WebDriver?
Stale Element Reference Exception in Selenium WebDriver: Troubleshooting and Resolution
Selenium WebDriver's Stale Element Reference Exception occurs when a previously obtained WebElement reference becomes invalid due to changes in the underlying DOM. This issue arises when elements are updated or removed dynamically, rendering the existing references obsolete.
Causes of the Exception
The exception can occur when:
Example Code and Exception Details
The provided code snippet experiences the exception during element recognition because the DOM changes when a dialog box opens and closes:
WebElement textElement = driver.findElement(By.name("createForm:dateInput_input"));
The error trace displays the following message:
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
Solution: Refresh the WebElement Reference
To resolve the issue, you need to refresh the WebElement reference after any DOM changes that could invalidate it. Commonly used solutions include:
WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("createForm:dateInput_input")));
WebElement textElement = (WebElement) ((JavascriptExecutor) driver) .executeScript("return document.querySelector('input[name=\"createForm:dateInput_input\"]')");
Additional Tips
The above is the detailed content of How to Resolve the Stale Element Reference Exception in Selenium WebDriver?. For more information, please follow other related articles on the PHP Chinese website!