我试图通过找到所有相应的“删除”按钮然后单击它们来删除页面上的多个元素。但是,当我从 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(); }
最佳答案
进行无限循环,当找不到更多“删除”按钮时退出:
while (true) {
try {
SeleniumCommands.waitClickByCss("[id^=removeForm_]");
} catch (TimeoutException e) {
break;
}
SeleniumCommands.waitClickById(ManageCommands.CONFIRMMODALOKBUTTON);
}
如有必要,请添加显式等待。
关于java - Selenium - 尝试单击多个 "Remove"按钮,但出现 StaleElementReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661645/