How to handle StaleElementReferenceException

有些话、适合烂在心里 提交于 2019-12-20 05:58:29

问题


I am working for a mouse hover and i want to test all the links working condition by clicking each and every link using for loop.In my program the iteration is going once and for the next iteration it is not working and showing the "StaleElementReferenceException".......... Please do modification in the code if required....

public static void main(String[] args) throws IOException 
{
  WebDriver driver = new FirefoxDriver();
Autoit.Authenti(driver);
    driver.manage().window().maximize();

    driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);

   driver.get("http://staging.zenrays.com");


   Actions a1=new Actions(driver);
   WebElement cl=driver.findElement(By.xpath(".//*[@id='menu-450-2']/a"));
   a1.moveToElement(cl).perform();

   WebDriverWait wait =new WebDriverWait(driver, 30);



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

           for(int i=0;i<=links.size()-1;i++)
           {

               links.get(i).click();

            driver.navigate().back();

               }
               }
          }

回答1:


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




回答2:


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

           }


来源:https://stackoverflow.com/questions/43307002/how-to-handle-staleelementreferenceexception

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