我在类开始时初始化一个变量:
public WebElement logout;
稍后在代码中,在某些方法中,第一次遇到注销按钮时,我为该变量赋值(在 if/else 语句的括号中):
logout = driver.findElement(By.linkText("Logout"));
logout.click();
然后我在测试的另一个阶段再次成功地使用“注销”:
logout.click();
并且在测试结束时,在元素相同的地方(By.linkText(“Logout”)),我得到这个错误:
Element not found in the cache - perhaps the page has changed since it was looked up
为什么?
编辑:实际上,我没有成功使用 logout.click();命令在我测试的另一个阶段。看来我不能再使用它了。我必须创建一个 logout1 网络元素并使用它...
最佳答案
如果在您最初找到元素
之后页面发生了任何更改,webdriver
引用现在将包含一个陈旧
引用。随着页面的更改,元素
将不再位于 webdriver
期望的位置。
要解决您的问题,请在每次需要使用元素时尝试查找
元素 - 编写一个您可以随时调用的小方法是个好主意。
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");
所以每次它都会找到该元素并单击它,因此即使页面发生变化,因为它正在“刷新”对该元素的引用,它都会成功单击它。
关于java - 带有 Java 的 Selenium Webdriver : Element not found in the cache - perhaps the page has changed since it was looked up,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17972359/