rahulserver rahulserver - 10 days ago 5
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();
webDriver.get(SEARCH_URL);
WebElement form2=webDriver.findElement(By.id("frmMain"));
form2.submit();
System.out.println(webDriver.getCurrentUrl());
List<WebElement>doctorAnchors=webDriver.findElements(By.xpath("//td[@class='data']/a"));
int count=0;
for(WebElement anchr:doctorAnchors){
anchr.click();
System.out.println((count++)+" : "+webDriver.getPageSource().toString());
Thread.sleep(10000);
webDriver.navigate().back();
}


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:
http://www.somepage.com/dispatch
whether I go to any anchor. I can navigate back in the web browser opened by the driver as usual. But why is this
webDriver.navigate().back()
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

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

driver.get("www.xyz.com");  
WebElement element = driver.findElement(By.id(Value));
List<WebElement> elements = element.findElements(By.tagName("a"));
int sizeOfAllLinks = elements.size();
System.out.println(sizeOfAllLinks);

for(int i=0; i<sizeOfAllLinks ;i++)
{
     System.out.println(elements.get(i).getAttribute("href"));
}

for (int index=0; index<sizeOfAllLinks; index++ )
{
     getElementWithIndex(By.tagName("a"), index).click();
     driver.navigate().back();
}

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