【问题标题】:Selenium WebDriver - StaleElementReferenceException when using click()Selenium WebDriver - 使用 click() 时出现 StaleElementReferenceException
【发布时间】:2014-03-03 14:30:02
【问题描述】:

有时当我执行这样的代码时:

webDriver.findElement(By.xpath("//*[@class='classname']")).click();

我得到了这个例外: org.openqa.selenium.StaleElementReferenceException:元素不再附加到 DOM 我知道我可以重试,但有谁知道为什么会发生这种情况以及如何防止它发生?

【问题讨论】:

  • 似乎该元素已从 Document 中删除。也许一些javascript删除了它。也许您的代码执行速度太快,并且该元素没有出现在一些 javascript 逻辑之后?

标签: java selenium-webdriver


【解决方案1】:

我遇到了同样的问题。

我的解决办法是:

webDriver.clickOnStableElement(By.xpath("//*[@class='classname']"));
...
        public void clickOnStableElement(final By locator) {
            WebElement e = new WebDriverWait(driver, 10).until(new ExpectedCondition<WebElement>(){
                public WebElement apply(WebDriver d) {
                   try {
                       return d.findElement(locator);
                   } catch (StaleElementReferenceException ex) {
                       return null;
                   }
               }
            });
            e.click();
         }  

希望对您有所帮助。 ;)

【讨论】:

  • 这对我很有帮助。非常感谢。
【解决方案2】:
webDriver.findElement(By.xpath("//*[@class='classname']"))

返回一个 WebElement 对象。

WebElement 对象始终引用 HTML DOM 树中的节点(在您的网络浏览器的内存中)。

当 DOM 树中的节点不再存在时,您会遇到此异常。 WebElement 对象仍然存在,因为它位于 JVM 的内存中。这是一种“断开的链接”。您可以在 WebElement 上调用方法,但它们会失败。

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 2017-11-16
    • 2014-11-15
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多