1

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.

  • the DOM is either still updating, or it's updating after the scroll. Chances are you don't need that scroll. The click method will automatically scroll into view. You can try/catch the click call if needed... if stale element exception is caught, re-get the element. (OR just use a sleep of a set amount of time after scroll, or before you get the element, depending on what's causing the stale element.) – pcalkins Sep 22 '21 at 18:54
  • I added the scroll 'cause it helped me prevent some other exception, but it's probably a different issue altogether. – Franco Agustín Rodriguez Sep 24 '21 at 16:11

1 Answers1

0

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

Prophet
  • 32,350
  • 22
  • 54
  • 79