在Fluent Wait中处理NoSuchElementException [英] Handle the NoSuchElementException in Fluent Wait

查看:134
本文介绍了在Fluent Wait中处理NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道就等待尚未在DOM中的Web元素而言,最有效的方法是流畅的等待.所以我的问题是:

I know that in terms of waiting for web element that isn't in the DOM yet, the most efficient is a fluent wait. So my question is:

是否存在一种方法来处理和捕获NoSuchElementException或由于该元素不存在而可能导致流畅等待的异常?

Is there a way to handle and catch the NoSuchElementException or any exception that fluent wait might throw because the element is not existing?

我需要一个布尔方法,其中无论是否找到该元素,它都会给我结果.

I need to have a boolean method wherein it will give me result whether the element is found or not.

此方法在网络上非常流行.

This method is quite popular on the web.

public void waitForElement(WebDriver driver, final By locator){
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(60, TimeUnit.SECONDS)
            .pollingEvery(2, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);

   wait.until(new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    });
}

我需要的是,**.ignoring(NoSuchElementException.class);**不会被忽略.并且一旦捕获到异常,它将返回FALSE.另一方面,当找到一个元素时,它将返回TRUE.

What I need is, **.ignoring(NoSuchElementException.class);** will not be ignored. And once the exception is caught, it will return FALSE. On the other hand, when an element is found, it will return TRUE.

推荐答案

作为替代方案,您希望查看

As an alternative as you have wanted to see the implementation of WebDriverWait with polling, here are the constructor details :

  • WebDriverWait(WebDriver driver, long timeOutInSeconds):Wait将忽略在直到"条件下默认遇到(抛出)的NotFoundException实例,并立即传播所有其他实例.

  • WebDriverWait(WebDriver driver, long timeOutInSeconds): Wait will ignore instances of NotFoundException that are encountered (thrown) by default in the 'until' condition, and immediately propagate all others.

WebDriverWait wait1 = new WebDriverWait(driver, 10);

  • WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis):等待将忽略在直到"条件下默认遇到(抛出)的NotFoundException实例,并立即传播所有其他实例.

  • WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis): Wait will ignore instances of NotFoundException that are encountered (thrown) by default in the 'until' condition, and immediately propagate all others.

    WebDriverWait wait2 = new WebDriverWait(driver, 10, 500);
    

  • 要回答您的评论,您需要在此处定义 WebDriverWait 实例.接下来,我们必须实现

    To answer to your comment, you need to define the WebDriverWait instance here. Next we have to implement the WebDriverWait instance i.e. wait1 / wait2 within your code through proper ExpectedConditions clauses.

    这篇关于在Fluent Wait中处理NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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