gpt4 book ai didi

java - 带有 Java 的 Selenium Webdriver : Element not found in the cache - perhaps the page has changed since it was looked up

转载 作者:太空狗 更新时间:2023-10-29 22:53:01 26 4
gpt4 key购买 nike

我在类开始时初始化一个变量:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com