【问题标题】:How to handle stale element reference: element is not attached to the page document [duplicate]如何处理陈旧的元素引用:元素未附加到页面文档[重复]
【发布时间】:2020-06-29 10:48:54
【问题描述】:

我有一个应用程序,我必须等待页面上显示一个按钮并单击它。该按钮是具有 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));

但我得到了同样的错误。

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

【问题讨论】:

  • 尝试使用 Xpath 搜索元素并执行包含这样的操作 //div[contains(@id,'recorder')]//button[@id='next-arrow-button']

标签: java selenium selenium-webdriver ui-automation staleelementreferenceexception


【解决方案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;
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2021-12-15
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多