Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

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

Upvotes: 16

Views: 52082

Answers (3)

user1134181
user1134181

Reputation:

The browser rebuilds the DOM structure of the dynamic pages, so the elements do not need to keep you have to find them before to use.

Using XPath, for example. This approach is not correct(can cause exception org.openqa.selenium.StaleElementReferenceException in the future):

WebElement element = driver.findElement(By.xpath("//ul[@class=\"pagination\"]/li[3]/a"));
...// Some Ajax interaction here
element.click(); //<-- Element might not be exists

This approach is correct:

driver.findElement(By.xpath("//ul[@class=\"pagination\"]/li[3]/a")).click();

Upvotes: 0

Mark Rowlands
Mark Rowlands

Reputation: 5453

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.

Upvotes: 31

Tester
Tester

Reputation: 1

This is because you are not giving proper time to load the page.So you have to give Thread.sleep(); code for the Given page.
I am also getting the same issue for my project but after using the Thread.sleep(); its working fine for me give the web page as much as it is possible for 30 to 50 secs.

Upvotes: -7

Related Questions