How to Solve stale element reference: element is not attached to the page document

1. Phenomenon

When executing a script, sometimes some element objects will throw the following exception

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

2. Cause of error

The official explanation is as follows:

The element has been deleted entirely.
The element is no longer attached to the DOM.

I personally understand that:

That is, the page element is out of date, the referenced element is out of date, and it is no longer attached to the current page, so the element object needs to be relocated

If JavaScript refreshes the web page, it will encounter a stale element reference exception during operation

Official address: http://docs.seleniumhq.org/exceptions/stale_ element_ reference.jsp

Solution:

The constructor of the webdriverwait class accepts a webdriver object and a maximum waiting time (30 seconds). The until method is then invoked, where the apply method in the ExpectedCondition interface is rewritten, so that it returns a WebElement, that is, the finished element, and then clicks. By default, webdriverwait calls expectedcondition every 500 milliseconds until it returns successfully. Of course, if it does not return successfully after exceeding the set value, it will throw an exception and loop for five times to search. The actual experiment shows that although the function tries five times at most, it generally queries three times at most, and there is no error, which is much better than thread waiting

The code is as follows:

/**
     * Wait for the text of the specified element to appear
     *
     * @param xpath
     * @param text
     * @return
     * @throws Exception
     */
    public Boolean isDisplay(final String xpath, final String text) {
        logger.info("Wait for the specified element text to be displayed");
        boolean result = false;
        int attempts = 0;
        while (attempts < 5) {
            try {
                attempts++;
                logger.info("The scan start element starts the first" + attempts + "次");
                result = new WebDriverWait(driver, 30)
                        .until(new ExpectedCondition<Boolean>() {
                            public Boolean apply(WebDriver driver) {
                                return driver.findElement(By.xpath(xpath)).getText().contains(text);
                            }
                        });
                logger.info("End of scan start element");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

Similar Posts: