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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29082862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:19:47  来源:igfitidea点击:

How to wait until an element no longer exists in Selenium

javaseleniumselenium-webdriver

提问by Thunderforge

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.

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

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:

我曾尝试使用ExpectedConditions.not()to invert ExpectedConditions.presenceOfElementLocated(),希望这意味着“期望不存在指定的元素”。我的代码是这样的:

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

However, I found that even doing this, I get a TimeoutExpcetioncaused by a NoSuchElementExceptionsaying 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.

但是,我发现即使这样做,我也会因为元素“foo”不存在TimeoutExpcetionNoSuchElementException说法而受到影响。当然,没有这样的元素是我想要的,但我不希望抛出异常。

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).

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

采纳答案by Vivek Singh

You can also use -

您还可以使用 -

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

If you go through the sourceof it you can see that both NoSuchElementExceptionand staleElementReferenceExceptionare handled.

如果你去通过的它,你可以看到,无论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;
        }
      }

回答by alecxe

The solution would still rely on exception-handling. And this is pretty much ok, even standard Expected Conditionsrely on exceptions being thrown by findElement().

该解决方案仍将依赖于异常处理。这几乎没问题,即使是标准的预期条件也依赖于findElement().

The idea is to create a custom Expected Condition:

这个想法是创建一个自定义的预期条件

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

回答by Saifur

Why don't you simply find the size of elements. We know the the collection of elements' sizewould be 0if elementdoes not exist.

你为什么不简单地找到elements. 我们知道如果元素不存在,元素集合的大小将为0

if(driver.findElements(By.id("foo").size() > 0 ){
    //It should fail
}else{
    //pass
}

回答by Nagaraju

// pseudo code
public Fun<driver,webelement> ElemtDisappear(locator)
{
    webelement element=null;
    iList<webelement> elemt =null;
    return driver=>
    {
    try
    {
    elemt = driver.findelements(By.locator);
    if(elemt.count!=0)
    {
    element=driver.findelement(By.locator);
    }
    }
    catch(Exception e)
    {
    }
    return(elemnt==0)?element:null;
};

// call function
public void waitforelemDiappear(driver,locator)
{
    webdriverwaiter wait = new webdriverwaiter(driver,time);
    try
    {
    wait.until(ElemtDisappear(locator));
    }
    catch(Exception e)
    {
    }
}

As findelement throws exception on element unaviability.so i implemented using findelements. please feel free to correct and use it as per your need.

由于 findelement 在元素 unaviability.so 上引发异常,所以我使用 findelement 实现。请随时根据您的需要更正和使用它。

回答by Abhinav Saxena

I found a workaround to fix this for me in efficient way, used following C# code to handle this, you may convert it to Java

我找到了一种解决方法以有效的方式为我解决此问题,使用以下 C# 代码来处理此问题,您可以将其转换为 Java

    public bool WaitForElementDisapper(By element)
    {
        try
        {
            while (true)
            {
                try
                {
                    if (driver.FindElement(element).Displayed)
                        Thread.Sleep(2000);
                }
                catch (NoSuchElementException)
                {
                    break;
                }
            }
            return true;
        }
        catch (Exception e)
        {
            logger.Error(e.Message);
            return false;
        }
    }

回答by Huy Hóm H?nh

I don't know why but ExpectedConditions.invisibilityOf(element)is the only work for me while ExpectedConditions.invisibilityOfElementLocated(By), !ExpectedConditions.presenceOfElementLocated(By)... not. Try it!

我不知道为什么,但是ExpectedConditions.invisibilityOf(element)是唯一为我工作,同时ExpectedConditions.invisibilityOfElementLocated(By)!ExpectedConditions.presenceOfElementLocated(By)...不是。尝试一下!

Hope this help!

希望这有帮助!