如何等待元素在 Selenium 中不再存在 [英] How to wait until an element no longer exists in Selenium

查看:23
本文介绍了如何等待元素在 Selenium 中不再存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am testing a UI in which the user clicks a delete button and a table entry disappears. As such, I want to be able to check that the table entry no longer exists.

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

I have tried using ExpectedConditions.not() to invert ExpectedConditions.presenceOfElementLocated(), hoping that it would mean "expect that there is not a presence of the specified element". My code is like so:

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

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

However, I found that even doing this, I get a TimeoutExpcetion caused by a NoSuchElementException saying that the element "foo" does not exist. Of course, having no such element is what I want, but I don't want an exception to be thrown.

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

So how can I wait until an element no longer exists? I would prefer an example that does not rely on catching an exception if at all possible (as I understand it, exceptions should be thrown for exceptional behavior).

推荐答案

你也可以使用 -

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

如果你通过 源码 你可以看到 NoSuchElementExceptionstaleElementReferenceException 都被处理了.

If you go through the source of it you can see that both NoSuchElementException and staleElementReferenceException are handled.

/**
   * 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;
        }
      }

这篇关于如何等待元素在 Selenium 中不再存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆