0

我有一个应用程序,我必须等待页面上显示一个按钮并单击它。该按钮是具有 id="next-arrow-button" 的按钮,但在父 div 上它具有 id="recorder-0"

在此处输入图像描述

按下此按钮后,该按钮将在几秒钟内不再显示。

该按钮再次显示如下: 在此处输入图像描述

您可以看到它具有相同的 id(id="next-arrow-button"),但在父 div 上它有另一个 id(id="recorder- 1 ",在它是 recoder- 0之前)

我等待元素可见并尝试单击它,但出现此错误:

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

我的代码有点乱,但我想和你分享一个版本:

 WebElement firstRecording = new WebDriverWait(driver, Constant.TIMEOUT_SECOND).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#recorder-0 #next-arrow-button")));
        firstRecording.click();


        new WebDriverWait(driver, Constant.TIMEOUT_SECOND).until(ExpectedConditions.stalenessOf(firstRecording));



        WebElement secondRecording = new WebDriverWait(driver, Constant.TIMEOUT_SECOND).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#recorder-1 #next-arrow-button")));
        secondRecording.click();

我试图删除该行:

new WebDriverWait(driver, Constant.TIMEOUT_SECOND).until(ExpectedConditions.stalenessOf(firstRecording));

但我得到同样的错误。

我是初级,如果我犯了一个愚蠢的错误,我很抱歉,但我真的需要你的帮助。谢谢 :)

4

1 回答 1

1

我设法在这里找到了解决方案。忘记 selenium 的等待并使用 Java 代码:

 public void customWaitAndClick(WebDriver driver, String CSSelement) {
        boolean flag = true;
        long currentTime = System.currentTimeMillis();
        long end = currentTime + 60000L;

        while (!flag || System.currentTimeMillis() < end) {
            try {
                driver.findElement(By.cssSelector(CSSelement)).click();
                break;
            } catch (Exception e) {
                flag = false;
            }
        }
    }
于 2020-03-18T13:20:20.390 回答