0

I was running some selenium automation tests in TestNG(Java), I am getting org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document this error. I was trying to debug this, Can someone help me to fix this issue on multiple pages. My test has almost 2000 lines, I was randomly getting this error. I am using explicit wait and Thread.sleep in code.

thanks

JeffC
  • 22,180
  • 5
  • 32
  • 55
raja
  • 3
  • 3
  • 1
    Can you isolate the problem into something significantly smaller than 2000 lines? – jsheeran May 01 '18 at 16:04
  • Are you using page objects? – Bill Hileman May 01 '18 at 17:02
  • @BillHileman Yes, I am using page object model. I am initializing elements using lazy initialization. – raja May 01 '18 at 17:09
  • Depending on the sequence of steps, you might need to re-create certain page objects instead of attempting to share them among methods. – Bill Hileman May 01 '18 at 18:07
  • To elaborate on my comment, the only time I've ever encountered a stale element exception, I was able to resolve the problem simply be re-instantiating the page object in the step (test method) in question. I realize there are other causes, but I've never encountered them myself. – Bill Hileman May 01 '18 at 18:21

2 Answers2

1

StaleElementException occurs, if we find an element, and DOM gets updated after that, we try to interact with the element.

If Javascript updates the page between the findElement call and the click call then we may get a StaleElementException. It is not uncommon for this to occur on modern web pages. It will not happen consistently however. The timing has to be just right for this bug to occur.

Code that you can try out !

public boolean retryingFindClick(By by) {
        boolean result = false;
        int attempts = 0;
        while(attempts < 2) {
            try {
                driver.findElement(by).click();
                result = true;
                break;
            } catch(StaleElementException e) {
            }
            attempts++;
        }
        return result;
}

For more reference you can check this tutorial : Stale Element Refernce

cruisepandey
  • 28,520
  • 6
  • 20
  • 38
0

You could try using FluentWait as an alternative to explicit wait and Thread.sleep. FluentWait will allow you to define the maximum amount of time to wait for a condition, the polling interval and the type of exception to ignore.

String xpath = "//somexpath";

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(StaleElementReferenceException.class);

WebElement someElement = wait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.xpath(xpath));
    }
});
Josh Sullivan
  • 360
  • 3
  • 10