如何等到元素不再存在于 Selenium 中

新手上路,请多包涵

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

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

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

但是,我发现即使这样做,我也会得到一个 TimeoutExpcetionNoSuchElementException 引起,说元素“foo”不存在。当然,没有这样的元素是我想要的,但我不想抛出异常。

那么我怎么能等到一个元素不再存在呢?我更喜欢一个尽可能不依赖于捕获异常的示例(据我了解,应该为异常行为抛出异常)。

原文由 Thunderforge 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 365
2 个回答

您还可以使用 -

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

如果你浏览它 的源代码,你可以看到 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;
        }
      }

原文由 Vivek Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

该解决方案仍然依赖于异常处理。这很好,即使是 标准的预期条件 也依赖于 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;
      }
    };
  }

原文由 alecxe 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题