首页 > 解决方案 > org.openqa.selenium.StaleElementReferenceException:过时元素引用:元素未附加到页面文档以查找元素

问题描述

我使用此代码单击

List<WebElement> list = driver.findElements(By.xpath("//div[@class='ag-center-cols-container']//div"));

        // check for list elements and print all found elements
        if(!list.isEmpty())
        {
            for (WebElement element : list)
            {
//                System.out.println("Found inner WebElement " + element.getText());
            }
        }

        // iterate sub-elements
        for ( WebElement element : list )
        {
            System.out.println("Searching for " + element.getText());

            if(element.getText().equals(valueToSelect))
            {
                new WebDriverWait(driver, 30).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='overlay ng-star-inserted']")));

                element.click();
                break;  // We need to put break because the loop will continue and we will get exception
            }
        }

但有时我会在这一行收到此错误element.getText()

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

你知道我如何实现一个lister来解决这个问题>

标签: seleniumselenium-webdriverselenium-chromedriver

解决方案


org.openqa.selenium.StaleElementReferenceException:

表示对元素的引用现在是“陈旧的”——该元素不再出现在页面的 DOM 上。这种期望的原因可能是你DOM得到了更新或刷新。例如,在执行类似click()您的操作后,DOM可能会得到更新或刷新。在这个时候,当你试图在你上面找到一个元素时,DOM你会遇到这个错误。

您必须在更新或刷新中重新找到该元素DOM

但有时我会在这一行 element.getText() 收到此错误:

创建一个可重用的方法来处理此异常。

代码

public static String getTextFromElement(WebElement element, WebDriver driver) {
    try {
        return element.getText();
    } catch (org.openqa.selenium.StaleElementReferenceException e) {
        new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOf(element));
        return element.getText();
    }
}

例如,您可以通过这种方式调用。

System.out.println("Found inner WebElement " + getTextFromElement(element, driver));

推荐阅读