如何处理StaleElementReferenceException

时间:2017-04-09 13:04:23

标签: java selenium-webdriver mouseover

我正在为鼠标悬停工作,我希望通过使用for循环点击每个链接来测试所有链接的工作条件。在我的程序中,迭代进行一次,对于下一次迭代,它不起作用并显示" StaleElementReferenceException" .......... 如果需要,请在代码中进行修改....

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

               }
               }
          }

2 个答案:

答案 0 :(得分:1)

理解一个基本的东西:staleElementReferenceException,它的名字表明对页面上元素的引用是陈旧的(丢失)。如果它们可用,您只需要再次引用这些元素,在这种情况下,由于页面已刷新,因此很容易。做两件事:

  1. 刷新页面后(当您向后导航时),使用显式等待直到您期望的元素可见
  2. 然后,新引用您想要再次使用的元素(已使用的xpath定位器)
  3. 作为干净优雅的代码,在这些场景中使用try-catch块
  4. 我不会直接给你代码:)试试看,然后再回复你的代码。

    参考here 为此明确解释此特定异常的可能方案

    还有一件事:你的for循环给出IndexOutOfBoundsException。同样修改

答案 1 :(得分:0)

您可以在代码中使用以下修改: -

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

           }