我正在测试一个用户界面,其中用户单击删除按钮,并且表条目消失。因此,我希望能够检查表条目是否不再存在。

我尝试使用ExpectedConditions.not()反转ExpectedConditions.presenceOfElementLocated(),希望它的意思是“期望不存在指定的元素”。我的代码是这样的:

browser.navigate().to("http://stackoverflow.com");
new WebDriverWait(browser, 1).until(
        ExpectedConditions.not(
                ExpectedConditions.presenceOfElementLocated(By.id("foo"))));

但是,我发现即使执行此操作,我也会收到由TimeoutExpcetion引起的NoSuchElementException,说元素“foo”不存在。当然,我想要的是没有这样的元素,但是我不希望引发异常。

那么,如何等待直到元素不再存在?我希望有一个示例,该示例尽可能不依赖于捕获异常(据我所知,异常行为应引发异常)。

最佳答案

您还可以使用-

new WebDriverWait(driver, 10).until(ExpectedConditions.invisibilityOfElementLocated(locator));

如果您仔细阅读the source,可以看到NoSuchElementExceptionstaleElementReferenceException均已处理。
/**
   * An expectation for checking that an element is either invisible or not
   * present on the DOM.
   *
   * @param locator used to find the element
   */
  public static ExpectedCondition<Boolean> invisibilityOfElementLocated(
      final By locator) {
    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) {
        try {
          return !(findElement(locator, driver).isDisplayed());
        } catch (NoSuchElementException e) {
          // Returns true because the element is not present in DOM. The
          // try block checks if the element is present but is invisible.
          return true;
        } catch (StaleElementReferenceException e) {
          // Returns true because stale element reference implies that element
          // is no longer visible.
          return true;
        }
      }

关于java - 如何等待直到 Selenium 中不再存在元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29082862/

10-11 02:42
查看更多