J. K. J. K. - 1 year ago 63
Java Question

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;

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"));

I then use "logout" once more, successfully, at another stage of my test:


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


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...

Answer Source

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 finding 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) {

Then within your code you'd only need to:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download