关于报错stale element reference: element is not attached to the page document处理

1、现象

在执行脚本时,有时候引用一些元素对象会抛出如下异常

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。

官方地址:http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp

解决方案:

使用WebDriverWait类的构造方法接受了一个WebDriver对象和一个等待最长时间(30秒)。然后调用until方法,其中重写了ExpectedCondition接口中的apply方法,让其返回一个WebElement,即加载完成的元素,然后点击。默认情况下,WebDriverWait每500毫秒调用一次ExpectedCondition,直到有成功的返回,当然如果超过设定的值还没有成功的返回,将抛出异常,循环五次查找,实际实验发现,函数里虽然最多尝试5次,但是一般也就查询最多3次,也在没有报错,比起线程等待要好很多,

代码如下:

/**
     * 等待指定元素文本出现
     *
     * @param xpath
     * @param text
     * @return
     * @throws Exception
     */
    public Boolean isDisplay(final String xpath, final String text) {
        logger.info("等待指定元素文本显示");
        boolean result = false;
        int attempts = 0;
        while (attempts < 5) {
            try {
                attempts++;
                logger.info("扫描开始元素开始第" + attempts + "次");
                result = new WebDriverWait(driver, 30)
                        .until(new ExpectedCondition<Boolean>() {
                            public Boolean apply(WebDriver driver) {
                                return driver.findElement(By.xpath(xpath)).getText().contains(text);
                            }
                        });
                logger.info("扫描开始元素结束");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值