Back to All Scenarios
Scenario 73 of 100
Exceptions
Advanced
Resolving Intermittent Stale Element References
πScenario Overview
Resolving Intermittent Stale Element References
Key Takeaways & Cheat Sheet
- βIdentify asynchronous elements updated by setInterval or dynamic AJAX polls
- βWrap wait statements using ExpectedConditions.refreshed()
- βEnsure WebElements are queried dynamically rather than saved inside base constructors
- βWrite clean try-catch action wrappers that automatically retry on staleness
Short Direct Answer
Stale element exceptions happen when Javascript updates the DOM and replaces an active node. To resolve this, avoid saving WebElement references as class fields. Instead, wrap your explicit waits with `ExpectedConditions.refreshed()`, which instructs Selenium to automatically re-query the DOM if the element becomes stale.
β οΈ Senior Warning (Red Flag)
Do not use Page Factory caching (@CacheLookup) for elements that render dynamically. This causes immediate stale element exceptions when the container updates.
π‘ STAR Deep Dive Explanation & Pro Tip
The refreshed() utility works by catching StaleElementReferenceException behind the scenes and immediately triggering another lookup, keeping your tests highly resilient.
SeleniumAutomation.java
Selenium 4 + Java// β
Strategy: Wrap wait check in 'refreshed()' to force dynamic re-locating
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement dynamicBtn = wait.until(
ExpectedConditions.refreshed(
ExpectedConditions.elementToBeClickable(By.id("confirm-payment-btn"))
)
);
dynamicBtn.click();