How to handle StaleElementReferenceException

前端 未结 2 995
谎友^
谎友^ 2021-01-28 02:35

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 fo

相关标签:
2条回答
  • 2021-01-28 03:13

    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();
    
               }
    
    0 讨论(0)
  • 2021-01-28 03:23

    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

    0 讨论(0)
提交回复
热议问题