title: StaleElementReferenceException while navigating back in selenium WebDriver
body: <p>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:</p>
  
  <pre><code>        WebDriver webDriver=new FirefoxDriver();
          webDriver.get(SEARCH_URL);
          WebElement form2=webDriver.findElement(By.id("frmMain"));
          form2.submit();
          System.out.println(webDriver.getCurrentUrl());
          List&lt;WebElement&gt;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();
          }
  </code></pre>
  
  <p>The code just goes through the first element in Anchors, performs click, gets the page, but when I navigate backwards, it gives:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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: <code>http://www.somepage.com/dispatch</code> whether I go to any anchor. I can navigate back in the web browser opened by the driver as usual. But why is this <code>webDriver.navigate().back()</code> 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?</p>