带有Java的Selenium Webdriver:在缓存中找不到元素 - 也许页面在查找后已经发生了变化 [英] Selenium Webdriver with Java: Element not found in the cache - perhaps the page has changed since it was looked up
问题描述
我正在我的课程开头初始化一个变量:
I am initializing a variable in the beginning of my class:
public WebElement logout;
稍后在代码中,在某些方法中,第一次遇到注销按钮时,我分配了该变量的值(在if / else语句的括号中):
Later on in the code, in some method, the first time I encounter the logout button, I assign a value to that variable (in the brackets of an if/else statement):
logout = driver.findElement(By.linkText("Logout"));
logout.click();
然后我在测试的另一个阶段成功再次使用logout:
I then use "logout" once more, successfully, at another stage of my test:
logout.click();
在测试结束时,在元素相同的地方(By.linkText (退出)),我收到此错误:
And at the end of the test, at a place where the element is the same (By.linkText ("Logout")), I get this error:
Element not found in the cache - perhaps the page has changed since it was looked up
为什么?
编辑:实际上,我没有成功使用logout.click();在我测试的另一个阶段。看起来我不能再使用它了。我必须创建一个logout1 webelement并使用它...
Actually, I dont successfully use the logout.click(); commant at another stage of my test. Looks like I cant use it again. I have to create a logout1 webelement and use it...
推荐答案
如果您有页面后有任何更改最初发现元素
webdriver
引用现在将包含陈旧
参考。当页面发生变化时,元素
将不再是 webdriver
所期望的那样。
If there has been any changes to the page after you have initially found the element
the webdriver
reference will now contain a stale
reference. As the page has changed, the element
will no longer be where webdriver
expects it to be.
要解决您的问题,请在每次需要使用时尝试找到
元素 - 编写一个可以调用的小方法何时是一个好主意。
To solve your issue, try find
ing the element each time you need to use it - writing a small method that you can call as and when is a good idea.
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();
}
然后在你的代码中你只需要:
Then within your code you'd only need to:
clickAnElementByLinkText("Logout");
所以每次找到元素并点击它,即使页面改变为它是刷新对该元素的引用,它都成功地单击它。
So each time it will find the element and click on it, as such even if the page changes as it is 'refreshing' the reference to that element it all successfully click it.
这篇关于带有Java的Selenium Webdriver:在缓存中找不到元素 - 也许页面在查找后已经发生了变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!