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

J. *_* K. 15 java selenium webdriver

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

public WebElement logout;
Run Code Online (Sandbox Code Playgroud)

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

logout = driver.findElement(By.linkText("Logout"));
logout.click();
Run Code Online (Sandbox Code Playgroud)

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

logout.click();
Run Code Online (Sandbox Code Playgroud)

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

Element not found in the cache - perhaps the page has changed since it was looked up
Run Code Online (Sandbox Code Playgroud)

为什么?

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

Mar*_*nds 31

如果在您最初找到后对页面进行了任何更改,elementwebdriver引用现在将包含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();
}
Run Code Online (Sandbox Code Playgroud)

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

clickAnElementByLinkText("Logout");
Run Code Online (Sandbox Code Playgroud)

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

  • 如果在操作DOM的页面上运行javascript(例如,动态弹出窗口),则由于竞争条件仍然会抛出此异常. (2认同)