如何等待Selenium中的元素不再存在

Thu*_*rge 31 java selenium selenium-webdriver

我正在测试用户单击删除按钮的UI,表条目消失.因此,我希望能够检查表条目不再存在.

我试过使用ExpectedConditions.not()反转ExpectedConditions.presenceOfElementLocated(),希望它意味着"期望不存在指定的元素".我的代码是这样的:

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

但是,我发现即使这样做,我也会得到TimeoutExpcetion一个NoSuchElementException说法,即元素"foo"不存在.当然,没有这样的元素是我想要的,但我不想抛出异常.

那么我怎么能等到一个元素不再存在?我希望一个不依赖于捕获异常的示例(如我所知),应该抛出异常以用于异常行为).

Viv*_*ngh 48

你也可以用 -

new WebDriverWait(driver, 10).until(ExpectedConditions.invisibilityOfElementLocated(locator));
Run Code Online (Sandbox Code Playgroud)

如果你经过它的来源,你可以看到,无论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;
        }
      }
Run Code Online (Sandbox Code Playgroud)


ale*_*cxe 5

解决方案仍然依赖于异常处理.这是非常好的,即使标准的预期条件依赖于被抛出的异常findElement().

我们的想法是创建一个自定义的预期条件:

  public static ExpectedCondition<Boolean> absenceOfElementLocated(
      final By locator) {
    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) {
        try {
          driver.findElement(locator);
          return false;
        } catch (NoSuchElementException e) {
          return true;
        } catch (StaleElementReferenceException e) {
          return true;
        }
      }

      @Override
      public String toString() {
        return "element to not being present: " + locator;
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)