Skip to content

Stale element just after Find

I’m using ChromeDriver in Groovy, for clarification.

I know that you usually can get a Stale Element Exception if you save an element, the page changes and then you try to access it. But my problem is that I sometimes at random get that error when i literraly just obtained it.

My code looks something like this:

def elem = new WebDriverWait(driver, timeout).until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)))
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", elem)
elem.click()

And it’s on the elem.click() that I get the exception, which makes no sense to me.

Answer

There are several technologies to implement web pages. In some such technologies web elements are appearing and then re-built so that Selenium detects those elements as visible/clickable but the elements are immediately re-built so the initial reference becomes stale.
On of the simplest workarounds to work on such pages with Selenium is to use loops of try-catch like the below:

public boolean retryingFindClick(String xpath) {
    int attempts = 0;
    while(attempts < 5) {
        try {
            def elem = new WebDriverWait(driver, timeout).until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)))
            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", elem)
            elem.click()
            return true;
        } catch(StaleElementException e) {
        }
        attempts++;
    }
    return false;
}

See here for more details