【问题标题】:Selenium - Trying to click several "Remove" buttons, but getting StaleElementReferenceExceptionSelenium - 尝试单击几个“删除”按钮,但得到 StaleElementReferenceException
【发布时间】:2015-07-27 19:28:50
【问题描述】:

我试图通过找到所有相应的“删除”按钮然后单击它们来删除页面上的几个元素。但是,当我从 DOM 中删除元素并且不确定如何优雅地解决这个问题时,我收到了“StaleElementReferenceException”。

这是我的代码:

List<WebElement> removeButtons = SeleniumCommands.findElementsByCss("[id^=removeForm_]");
    System.out.println(removeButtons.size());
    for (int i = removeButtons.size()-1; i >= 0; i--) {
        SeleniumCommands.wait.until(ExpectedConditions.visibilityOf(removeButtons.get(i)));
        removeButtons.get(i).click();
        SeleniumCommands.waitClickById(ManageCommands.CONFIRMMODALOKBUTTON);
    }
}

这里是删除按钮的一些 HTML...

<input id="removeForm_615" class="btn remove-task btn-danger" type="button" form_id="615" value="Remove" name="removeForm_615"/>

每个 removeForm 在下划线后面都有一个唯一的 ID。

有没有一种更有效的方式从 DOM 中删除元素,以这种方式在 for 循环样式或类似方法中摆脱我的 StaleElementReferenceException?

更新:这是当前编辑的代码:

while (true) {
    try {
        SeleniumCommands.waitClickByCss("[id^=removeForm_]");
    } catch (NoSuchElementException e) {
        break;
    }
    SeleniumCommands.waitClickById(ManageCommands.CONFIRMMODALOKBUTTON);
    try { Thread.sleep(500); } catch (InterruptedException ie) { ie.getMessage(); }
}

当我这样做时,我得到一个TimeoutException,因为它仍在继续尝试查找By.selector: [id^=removeForm_]。如何修复它以使其按预期抛出NoSuchElementException

供参考:

public static void waitClickByCss(String css) { wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(css))).click(); }

【问题讨论】:

    标签: java html selenium selenium-webdriver


    【解决方案1】:

    创建无限循环,当你找不到更多“删除”按钮时退出它:

    while (true) {
        try {
            SeleniumCommands.waitClickByCss("[id^=removeForm_]");
        } catch (TimeoutException e) {
            break;
        }
    
        SeleniumCommands.waitClickById(ManageCommands.CONFIRMMODALOKBUTTON);
    }
    

    如有必要,请添加显式等待。

    【讨论】:

    • 嘿,alecxe,我真的很接近工作了。我确实有一个问题,请参阅原始帖子以获取更新。谢谢!
    • 另外,解释为什么我在try 内添加“点击”是因为在try 范围之外,removeButton.click(); 无法正常工作,因为无法保证removeButton存在。
    • @lmcphers 当然,只要抓住TimeoutException。已更新。
    • 再次感谢alecxe!对此,我真的非常感激。 :)
    • 好吧,我认为这很好而且很简单,但是我收到了一个编译器错误,提示 TimeoutException is never thrown in the corresponding try block。为什么会这样说?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2021-11-06
    • 2015-11-14
    相关资源
    最近更新 更多