Java Selenium WebDriver-使用click()时发生StaleElementReferenceException

Java Selenium WebDriver-使用click()时发生StaleElementReferenceException,java,selenium-webdriver,Java,Selenium Webdriver,有时当我执行这样的代码时: webDriver.findElement(By.xpath("//*[@class='classname']")).click(); 我得到一个例外: org.openqa.selenium.StaleElementReferenceException:元素不再附加到DOM 我知道我可以重试,但有人知道为什么会发生这种情况,以及我如何防止它吗 webDriver.findElement(By.xpath("//*[@class='classname']")) 返

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

webDriver.findElement(By.xpath("//*[@class='classname']")).click();
我得到一个例外: org.openqa.selenium.StaleElementReferenceException:元素不再附加到DOM 我知道我可以重试,但有人知道为什么会发生这种情况,以及我如何防止它吗

webDriver.findElement(By.xpath("//*[@class='classname']"))
返回一个WebElement对象

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


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

我也遇到了同样的问题

我的解决办法是:

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();
         }  
webDriver.clickOnTableElement(By.xpath(“/*[@class='classname']);
...
公共无效ClickOnTableElement(最终由定位器确定){
WebElement e=新的WebDriverWait(驱动程序,10)。直到(新的ExpectedCondition(){
公共WebElement应用(WebDriver d){
试一试{
返回d.findElement(定位器);
}捕获(StaleElementReferenceException ex){
返回null;
}
}
});
e、 单击();
}  

希望它能帮助你

似乎此元素已从文档中删除。也许是javascript删除了它。也许你的代码执行得太快了,而那个元素在一些javascript逻辑之后没有出现?看看这个-这真的帮助了我。非常感谢你。