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

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

问题描述

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

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"))));

然而,我发现即使这样做,我得到 TimeoutExpcetion NoSuchElementException 引起,表示元素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));

如果你查看它的来源,你可以看到 NoSuchElementException <处理/ code>和 staleElementReferenceException

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天全站免登陆