How to handle StaleElementReferenceException

烈酒焚心 提交于 2019-12-02 07:54:52

Understand one fundamental thing: staleElementReferenceException, by it's name suggests that the reference to your elements on the page is stale (lost). You just have to refer to those elements again, if they are available, which is apt in this case as the page has been refreshed. Do 2 things:

  1. once the page is refreshed (when you navigate back), use an explicit wait until an element you expect is visible
  2. Then, newly refer to your elements(xpath locator that you have used) you wanna work with again
  3. As a clean and elegant code use try-catch block in these scenarios

I'm not gonna give you the code directly:)Try it and come back with your code.

Refer here for it's clear explanation of possible scenarios for this particular exception

One more thing: Your for loop gives IndexOutOfBoundsException. Modify that as well

You can use following modification in your code:-

 List<WebElement>  links=driver.findElements(By.xpath("//a[contains(@class,'sf-depth-2')]"));

       for(int i=0;i<links.size();i++)
       {
     List<WebElement>  allLinks=driver.findElements(By.xpath("//a[contains(@class,'sf-depth-2')]"));
           allLinks.get(i).click();

        driver.navigate().back();

           }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!