Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 834
Kaloyan Roussev Avatar asked Jul 31 '13 13:07

Kaloyan Roussev


1 Answers

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

like image 105
Mark Rowlands Avatar answered Nov 02 '22 00:11

Mark Rowlands