selenium webdriver – Web element going stale between FluentWait and performing action

I’ve used something like this for years in production test suites.

/**
 * Clicks the element.
 * 
 * @param locator The By locator for the desired element.
 * @param timeOutSeconds How long to wait for the element in seconds.
 * @throws Exception If the element is not clickable within the timeout period.
 */
public void click(By locator, int timeOutSeconds) throws Exception {
    LocalDateTime expire = LocalDateTime.now().plusSeconds(timeOutSeconds);
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutSeconds));
    while (LocalDateTime.now().compareTo(expire) < 0) {
        try {
            wait.until(ExpectedConditions.elementToBeClickable(locator)).click();

            return;
        } catch (ElementClickInterceptedException | StaleElementReferenceException e) {
            // do nothing, loop again
        }
    }

    throw new Exception(String.format("Not able to click element <%s> within %ss.", locator, timeOutSeconds));
}

This is using WebDriverWait instead of FluentWait directly. WebDriverWait is just an ease of use wrapper around FluentWait. If you MUST use FluentWait, it can be adapted.

You’ll notice that if a stale element exception is thrown, we just try again. This is what you need to handle stale element exceptions because once a reference is bad, it can never be made good again without going to get the element again.

Read more here: Source link