I am initializing a variable in the beginning of my class:
public WebElement logout;
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();
I then use "logout" once more, successfully, at another stage of my test:
logout.click();
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
Why?
EDIT: 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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With