首页 > 其他 > 详细

关于报错stale element reference: element is not attach的解决思路

时间:2020-01-03 14:50:08      阅读:78      评论:0      收藏:0      [点我收藏+]

   

1、现象

在执行UI自动化测试脚本时,有时候引用一些元素对象会抛出如下异常
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

2、报错原因

官方给出解释如下: 
The element has been deleted entirely.
The element is no longer attached to the DOM.
我个人理解:
就是页面元素过期,引用的元素过时,不再依附于当前页面,需要重新定位获取元素对象
如果JavaScript把网页给刷新了,那么操作的时候就会碰到Stale Element Reference Exception。
 

解决方案:

使用WebDriverWait类的构造方法接受了一个WebDriver对象和一个等待最长时间(30秒)。
然后调用until方法,其中重写了ExpectedCondition接口中的apply方法,让其返回一个WebElement,即加载完成的元素,然后点击。
默认情况下,WebDriverWait每500毫秒调用一次ExpectedCondition,直到有成功的返回,当然如果超过设定的值还没有成功的返回,将抛出异常,循环五次查找。
实际上,函数里虽然最多尝试5次,但是一般也就查询最多3次,也再没有报错,比起直接用线程等待要好很多。
 
public Boolean isDisplay(final String xpath, final String text) {
     boolean result = false;
     int attempts = 0;
     while (attempts < 5) {
         try {
             attempts++;
             result = new WebDriverWait(driver, 30)
                     .until(new ExpectedCondition<Boolean>() {
                         public Boolean apply(WebDriver driver) {
                             return driver.findElement(By.xpath(xpath)).getText().contains(text);
                         }
                     });
             return true;
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
     return result;
  }

 

关于报错stale element reference: element is not attach的解决思路

原文:https://www.cnblogs.com/generalli2019/p/12144554.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!