带有Java的Selenium Webdriver:在缓存中找不到元素 – 也许页面在查找后已经发生了变化

我在我的课程开头初始化一个变量:

public WebElement logout; 

稍后在代码中,在某些方法中,第一次遇到注销按钮时,我为该变量赋值(在if / else语句的括号中):

 logout = driver.findElement(By.linkText("Logout")); logout.click(); 

然后,我在测试的另一个阶段成功地再次使用“logout”:

 logout.click(); 

在测试结束时,在元素相同的地方(By.linkText(“Logout”)),我收到此错误:

 Element not found in the cache - perhaps the page has changed since it was looked up 

为什么?

编辑:实际上,我没有成功使用logout.click(); 在我测试的另一个阶段。 看起来我不能再使用它了。 我必须创建一个logout1 webelement并使用它…

如果在最初找到element后对页面进行了任何更改,则webdriver引用现在将包含stale引用。 随着页面的变化, element将不再是webdriver期望的。

要解决您的问题,请在每次需要使用它时尝试find元素 – 编写一个可以调用的小方法,以及什么时候是个好主意。

 import org.openqa.selenium.support.ui.WebDriverWait public void clickAnElementByLinkText(String linkText) { wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText(linkText))); driver.findElement(By.linkText(linkText)).click(); } 

然后在你的代码中你只需要:

 clickAnElementByLinkText("Logout"); 

因此,每次它都会找到元素并单击它,因此即使页面发生更改,因为它“刷新”了对该元素的引用,它们都会成功单击它。

浏览器重建动态页面的DOM结构,因此元素不需要在使用之前必须找到它们。

例如,使用XPath。 这种方法不正确(将来可能导致exceptionorg.openqa.selenium.StaleElementReferenceException ):

 WebElement element = driver.findElement(By.xpath("//ul[@class=\"pagination\"]/li[3]/a")); ...// Some Ajax interaction here element.click(); //<-- Element might not be exists 

这种方法是正确的:

 driver.findElement(By.xpath("//ul[@class=\"pagination\"]/li[3]/a")).click(); 

这是因为你没有给它适当的时间加载页面。所以你必须给Thread.sleep(); 给定页面的代码。
我也为我的项目得到了同样的问题,但在使用Thread.sleep(); 它的工作正常我给网页尽可能多30到50秒。