rahulserver rahulserver - 1 year ago 140
Java Question

StaleElementReferenceException while navigating back in selenium WebDriver

I am trying to crawl through some anchors within a web page using Selenium WebDriver. The approach I can think of is getting the anchors in a list and performing click on each and navigating backwards after each click. Here is my code:

WebDriver webDriver=new FirefoxDriver();
WebElement form2=webDriver.findElement(By.id("frmMain"));
int count=0;
for(WebElement anchr:doctorAnchors){
System.out.println((count++)+" : "+webDriver.getPageSource().toString());

The code just goes through the first element in Anchors, performs click, gets the page, but when I navigate backwards, it gives:

Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 169 milliseconds

I went through various stackoverflow posts on the same exception, and realized that it may be caused by some javascript content in the page and it seems right also because the page url is:
whether I go to any anchor. I can navigate back in the web browser opened by the driver as usual. But why is this
failing? And how do I navigate back after clicking on link? Is there a way I could save the state of the driver and click and restore that state after clicking?

Answer Source

What I have given below is an example for your solution. Here, I have called a method, getElementWithIndex to do so.. This works!!

In this example, it captures all the links under specific frame|class|id and Navigate one by one

WebElement element = driver.findElement(By.id(Value));
List<WebElement> elements = element.findElements(By.tagName("a"));
int sizeOfAllLinks = elements.size();

for(int i=0; i<sizeOfAllLinks ;i++)

for (int index=0; index<sizeOfAllLinks; index++ )
     getElementWithIndex(By.tagName("a"), index).click();

public WebElement getElementWithIndex(By by, int index)
     WebElement element = driver.findElement(By.id(Value));
     List<WebElement> elements = element.findElements(By.tagName("a")); 
     return elements.get(index);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download