我知道当DOM树发生变化时会抛出异常,解决方法是在刷新后再次查找元素,但是...

我正在做以下手术:

    sessionsView.filterSession(sessionName);
    lockSession();
    approveSession();
    completeSession();

在执行开始时,此代码completeButton被禁用,如下所示:

<button _ngcontent-mfo-c209="" class="btn btn-default btn-xs pull-right" style="margin-right: 10px;" disabled="">Complete</button>

锁定和批准操作由rest API服务完成."批准完成"按钮启用后,我会在刷新后查找它,然后try 单击它.

public void completeSession() {
    By completeButtonByXpath = By.xpath("*//button[text()='Complete']");
    WebElement completeButton = driver.findElement(completeButtonByXpath);
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.elementToBeClickable(completeButton));
    completeButton.click();
}

但我收到

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

当我点击completeButton

我也try 过这样的等待

有什么解决办法吗?

推荐答案

当你在做

driver.findElement(completeButtonByXpath);

现在selenium正在寻找*//button[text()='Complete']个xPath.

可能在这个时候,它没有连接到HTML-DOMstaleness.

Solution:

  1. 一个非常简单的解决方案是将硬编码睡眠如下:

    Thread.sleep(5000);
    

现在找WebElement completeButton = driver.findElement(completeButtonByXpath);

  1. completeSession修改为只进行显式等待.

    public void completeSession() {
     By completeButtonByXpath = By.xpath("*//button[text()='Complete']");
     //WebElement completeButton = driver.findElement(completeButtonByXpath);
     WebDriverWait wait = new WebDriverWait(driver, 30);
     wait.until(ExpectedConditions.elementToBeClickable(completeButtonByXpath)).click();
    }
    
  2. 重试clicking次.

Code:

public void completeSession() {
    By completeButtonByXpath = By.xpath("*//button[text()='Complete']");
    WebElement completeButton = driver.findElement(completeButtonByXpath);
    int attempts = 0;
    while(attempts < 5) {
        try {
            completeButton.click();
            break;
        }
        catch(StaleElementReferenceException staleException) {
            staleException.printStackTrace();
        }
        attempts++;
    }
}

Java相关问答推荐

为什么JFrame paint()多次绘制同一点(或根本不绘制)?

RDX触发ChoiceBox转换器(并按字符串值排序)

具有默认分支的JUnit代码覆盖率切换声明

scanner 如何在执行hasNextLine一次后重新读取整个文件?

Java函数式编程中的双值单值映射

路径映射未发生

S的字符串表示是双重精确的吗?

Java .类参数不通过构造函数传递

是否在允许数组元素为空时阻止 idea 为空性警告?

基于调车场算法的科学计算器

解释左移在Java中的工作原理

如何从JNI方法正确调用NSOpenPanel以在正确的线程上运行?

如何让JavaFx应用程序识别依赖项?

测试容器无法加载类路径初始化脚本

A.ForEach与For(类型a:集合)

IntelliJ IDEA中的JavaFX应用程序无法在资源中找到CSS文件

JavaFX,GridPane:在GridPane的列中生成元素将保持所有列的宽度

根据应用程序 Select 的语言检索数据

为什么Spring要更改Java版本配置以及如何正确设置?

如何在Selenium上继续使用最新的WebDriver版本