我怎样才能让 Selenium-WebDriver 在 Java 中等待几秒钟?

新手上路,请多包涵

我正在研究 Java Selenium-WebDriver。我加了

driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

WebElement textbox = driver.findElement(By.id("textbox"));

因为我的应用程序需要几秒钟来加载用户界面。所以我设置了2秒implicitwait。但我 无法找到元素文本框

然后我添加 Thread.sleep(2000);

现在它工作正常。哪种方法更好?

原文由 Gnik 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 439
2 个回答

好吧,有两种类型的等待:显式等待和隐式等待。明确等待的想法是

WebDriverWait.until(condition-that-finds-the-element);

隐式等待的概念是

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

您可以在 此处 了解细节差异。

在这种情况下,我更喜欢使用显式等待(特别是 fluentWait ):

 public WebElement fluentWait(final By locator) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(30, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);

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

    return  foo;
};

fluentWait 函数返回您找到的网络元素。来自 fluentWait 的文档 : Wait 接口的实现可能会动态配置其超时和轮询间隔。每个 FluentWait 实例定义等待条件的最长时间,以及检查条件的频率。此外,用户可以配置等待以在等待时忽略特定类型的异常,例如在页面上搜索元素时出现 NoSuchElementExceptions。 您可以 在此处 获得详细信息

fluentWait 在您的情况下的用法如下:

 WebElement textbox = fluentWait(By.id("textbox"));

恕我直言,这种方法更好,因为您不知道确切的等待时间,并且在轮询间隔中,您可以设置任意时间值来验证元素的存在。问候。

原文由 eugene.polschikov 发布,翻译遵循 CC BY-SA 4.0 许可协议

这个线程有点旧,但我想我会发布我目前所做的(正在进行的工作)。

虽然我仍然遇到系统负载很重的情况,当我单击提交按钮(例如,login.jsp)时,所有三个条件(见下文)都返回 true 但下一页(例如, home.jsp) 还没有开始加载。

这是一个通用的等待方法,它接受一个 ExpectedConditions 列表。

 public boolean waitForPageLoad(int waitTimeInSec, ExpectedCondition<Boolean>... conditions) {
    boolean isLoaded = false;
    Wait<WebDriver> wait = new FluentWait<>(driver)
            .withTimeout(waitTimeInSec, TimeUnit.SECONDS)
            .ignoring(StaleElementReferenceException.class)
            .pollingEvery(2, TimeUnit.SECONDS);
    for (ExpectedCondition<Boolean> condition : conditions) {
        isLoaded = wait.until(condition);
        if (isLoaded == false) {
            //Stop checking on first condition returning false.
            break;
        }
    }
    return isLoaded;
}

我已经定义了各种可重用的 ExpectedConditions(下面是三个)。在此示例中,三个预期条件包括 document.readyState = ‘complete’、不存在“wait_dialog”和不存在“spinners”(表示正在请求异步数据的元素)。

只有第一个可以普遍应用于所有网页。

 /**
 * Returns 'true' if the value of the 'window.document.readyState' via
 * JavaScript is 'complete'
 */
public static final ExpectedCondition<Boolean> EXPECT_DOC_READY_STATE = new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
        String script = "if (typeof window != 'undefined' && window.document) { return window.document.readyState; } else { return 'notready'; }";
        Boolean result;
        try {
            result = ((JavascriptExecutor) driver).executeScript(script).equals("complete");
        } catch (Exception ex) {
            result = Boolean.FALSE;
        }
        return result;
    }
};
/**
 * Returns 'true' if there is no 'wait_dialog' element present on the page.
 */
public static final ExpectedCondition<Boolean> EXPECT_NOT_WAITING = new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
        Boolean loaded = true;
        try {
            WebElement wait = driver.findElement(By.id("F"));
            if (wait.isDisplayed()) {
                loaded = false;
            }
        } catch (StaleElementReferenceException serex) {
            loaded = false;
        } catch (NoSuchElementException nseex) {
            loaded = true;
        } catch (Exception ex) {
            loaded = false;
            System.out.println("EXPECTED_NOT_WAITING: UNEXPECTED EXCEPTION: " + ex.getMessage());
        }
        return loaded;
    }
};
/**
 * Returns true if there are no elements with the 'spinner' class name.
 */
public static final ExpectedCondition<Boolean> EXPECT_NO_SPINNERS = new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
        Boolean loaded = true;
        try {
        List<WebElement> spinners = driver.findElements(By.className("spinner"));
        for (WebElement spinner : spinners) {
            if (spinner.isDisplayed()) {
                loaded = false;
                break;
            }
        }
        }catch (Exception ex) {
            loaded = false;
        }
        return loaded;
    }
};

根据页面的不同,我可能会使用其中一个或全部:

 waitForPageLoad(timeoutInSec,
            EXPECT_DOC_READY_STATE,
            EXPECT_NOT_WAITING,
            EXPECT_NO_SPINNERS
    );

在以下类中也有预定义的 ExpectedConditions: org.openqa.selenium.support.ui.ExpectedConditions

原文由 Jeff Vincent 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题