【问题标题】:Selenium 2.0 WebDriver: Element is no longer attached to the DOM error using JavaSelenium 2.0 WebDriver:元素不再附加到使用 Java 的 DOM 错误
【发布时间】:2023-03-26 20:49:01
【问题描述】:

我将 PageObject/PageFactory 设计模式用于我的 UI 自动化。使用 Selenium 2.0 WebDriver,JAVA,我随机得到错误:org.openqa.selenium.StaleElementReferenceException:元素不再附加到 DOM,当我尝试这样的逻辑时:

@FindBy(how = HOW.ID, using = "item")
private List<WebElement> items

private void getItemThroughName(String name) {
    wait(items);

    for(int i = 0; i < items.size(); i++) {
        try {
            Thread.sleep(0500);
        } catch (InterruptedException e) { }

        this.wait(items);
        if(items.get(i).getText().contains(name)) {
            System.out.println("Found");
            break;
        }
    }
}

错误随机发生在 if 语句行,如您所见,我已经尝试了几件事来避免这种情况,比如睡一小段时间,或者再次等待元素,但都不是 100% 的时间

【问题讨论】:

  • 您的网页上是否有任何 JavaScript 可能会从页面中删除项目?
  • 您是否尝试过在 Selenium 中使用实际的显式等待方法?此错误通常是竞争条件问题。
  • 就像 Arran 说的:尝试使用 webdriver 的等待。使用 Thread.sleep() 是一种不好的做法,应该避免。您可能永远不知道 500 毫秒的间隔是否足够,因此会出现随机错误。尝试隐式/显式等待,甚至使用 FluentWait 类更进一步

标签: java dom automation webdriver selenium-webdriver


【解决方案1】:

首先,如果您确实有多个 ID 为“item”的元素,您应该记录一个错误或与网站上的开发人员联系以修复它。 ID 是唯一的。

由于问题上的 cmets 已经暗示您应该在这种情况下使用 ExplicitWait:

private void getItemThroughName(String name) {
    new WebDriverWait(driver, 30)
               .until(ExpectedConditions.presenceOfElementLocated(
                 By.xpath("id('item')[.='" + name + "']")
               ));
    // A timeout exception will be thrown otherwise
    System.out.println("Found");
}

【讨论】:

    猜你喜欢
    • 2014-10-05
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2014-07-15
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多