如何克服程序中的陈旧元素引用错误

时间:2017-11-23 07:34:48

标签: java selenium selenium-webdriver automation

我收到Stale元素错误。我试图克服它,但每次都失败了。

d.get("https://iaeme.com/ijciet/index.asp");
java.util.List<WebElement>link = d.findElements(By.className("lik"));
for (int k=1 ; k<= link.size();k++) {
    link.get(k).click();// stale element error goes here.
    Thread.sleep(2000);
    System.out.println(d.getCurrentUrl());
}

有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:0)

使用try块包围异常抛出语句并捕获staleElementReferenceException。

d.get("https://iaeme.com/ijciet/index.asp");
 java.util.List<WebElement>link = d.findElements(By.className("lik"));
        for (int k=1 ; k<= link.size();k++) {
            try{
              link.get(k).click();// stale element error goes here.
             Thread.sleep(2000);
             System.out.println(d.getCurrentUrl());
           }catch(StaleElementReferenceException e){
              // find the element again OR handle the exception in your way
               }
        }

其他方法是在每次迭代中找到元素。这将确保页面导航后webElement的新鲜度。 替换语句

 link.get(k).click(); 

用这个:

d.findElement(By.xpath("(//*[@class='lik'])["+k+"]")).click();

答案 1 :(得分:0)

尝试

 d.get("https://iaeme.com/ijciet/index.asp");
 java.util.List<WebElement>link = d.findElements(By.className("lik"));
        for (int k=1 ; k<= link.size();k++) {
             if(link.get(k).isDisplayed()){
               link.get(k).click();// stale element error goes here.
               Thread.sleep(2000);
               System.out.println(d.getCurrentUrl());
             }
        }