如何避免“StaleElementReferenceException”在Selenium? [英] How to avoid "StaleElementReferenceException" in Selenium?

查看:157
本文介绍了如何避免“StaleElementReferenceException”在Selenium?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java实现许多Selenium测试。有时,由于 StaleElementReferenceException ,我的测试失败了。你能否建议一些使测试更稳定的方法?

I'm implementing a lot of Selenium tests using Java. Sometimes, my tests fail due to a StaleElementReferenceException. Could you suggest some approaches to making the tests more stable?

推荐答案

如果页面上发生的DOM操作暂时发生,可能会发生这种情况导致元素无法访问。为了允许这些情况,您可以在最终抛出异常之前尝试在循环中多次访问该元素。

This can happen if a DOM operation happening on the page is temporarily causing the element to be inaccessible. To allow for those cases, you can try to access the element several times in a loop before finally throwing an exception.

尝试来自darrelgrainger.blogspot.com的这个出色的解决方案

public boolean retryingFindClick(By by) {
    boolean result = false;
    int attempts = 0;
    while(attempts < 2) {
        try {
            driver.findElement(by).click();
            result = true;
            break;
        } catch(StaleElementException e) {
        }
        attempts++;
    }
    return result;
}

这篇关于如何避免“StaleElementReferenceException”在Selenium?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆