【问题标题】:How to handle StaleElementReferenceException如何处理 StaleElementReferenceException
【发布时间】:2017-04-09 13:04:22
【问题描述】:

我正在为鼠标悬停工作,我想通过使用 for 循环单击每个链接来测试所有链接的工作条件。在我的程序中,迭代只进行一次,对于下一次迭代它不起作用并显示“陈旧元素引用异常”............ 如果需要,请在代码中进行修改......

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

               }
               }
          }

【问题讨论】:

  • 您能否提供更多有关您要执行的具体步骤的信息?
  • 请访问链接(“zenrays.com”),在那里你可以看到课程链接(页面标题),它是一个鼠标悬停链接,有13个子链接,我想测试每个以及通过单击并导航回主页的每个子链接,以便我使用 for 循环。它适用于第一个子链接并导航回主页也适用于第二次迭代它显示异常........ ..

标签: java selenium-webdriver mouseover


【解决方案1】:

了解一件基本的事情:staleElementReferenceException,顾名思义,页面上对您的元素的引用已过时(丢失)。您只需要再次引用这些元素(如果它们可用),这在这种情况下很合适,因为页面已被刷新。做两件事:

  1. 刷新页面后(当您向后导航时),使用显式等待,直到您期望的元素可见
  2. 然后,重新引用您想要再次使用的元素(您使用过的 xpath 定位器)
  3. 在这些场景中使用 try-catch 块作为简洁优雅的代码

我不会直接给你代码:)试试看,然后把你的代码回来。

参考here 因为它清楚地解释了这个特定异常的可能场景

还有一件事:你的 for 循环给出了IndexOutOfBoundsException。也修改一下

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多