首页 > 解决方案 > 我想使用 Fluent 等待根据元素的存在返回 true 或 false,该怎么做?

问题描述

我正在使用 Fluent 等待,我看到函数的返回值是 WebElement。但是,我想根据元素的存在来返回 true 或 false。我该怎么做?我参考这个页面 - https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

代码片段在这里 -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

   WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
     public WebElement apply(WebDriver driver) {
       return driver.findElement(By.id("foo"));
     }
   });

我尝试更改为下面,但它给了我错误 -

Wait 类型中的方法 until(Function) 不适用于参数 (new Function(){})

这是我改变的 -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(retryCount, TimeUnit.SECONDS)
                .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

        Boolean foo = wait.until(new Function<WebElement, Boolean>() {
            public Boolean apply(WebElement by) {
                return true;
            }
        });

我正在使用 Guava 版本 23.0、Selenium 3.0、Java 1.8。*

标签: javaselenium-webdriver

解决方案


如果只有元素可见性很重要,请尝试以下操作:-

FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
    wait.withTimeout(Duration.ofSeconds(20));
    wait.pollingEvery(Duration.ofSeconds(5));
    wait.ignoring(NoSuchElementException.class);

     boolean status = wait.until(new Function<WebDriver, Boolean>() {
        public Boolean apply(WebDriver driver) {
            return driver.findElement(By.name("q")).isDisplayed();
        }
    });

推荐阅读