如何让Selenium-WebDriver在Java中等待几秒钟? [英] How can I ask the Selenium-WebDriver to wait for few seconds in Java?

查看:622
本文介绍了如何让Selenium-WebDriver在Java中等待几秒钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Java Selenium-WebDriver。我添加了

I'm working on a Java Selenium-WebDriver. I added

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

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

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

because my Applications takes few seconds to load the User Interface. So I set 2 seconds implicitwait. but I got unable to locate element textbox

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

现在工作正常。哪一个更好?

Now it works fine. Which one is a better way?

推荐答案

嗯,有两种类型的等待:显式和隐式等待。
显式等待的想法是

Well, there are two types of wait: explicit and implicit wait. The idea of explicit wait is

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

隐式等待的概念是

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

您可以获得详细信息这里

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

In such situations I'd prefer using explicit wait (fluentWait in particular):

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 function returns your found web element. From the documentation on fluentWait: An implementation of the Wait interface that may have its timeout and polling interval configured on the fly. Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page. Details you can get here

在你的情况下使用 fluentWait 如下:

Usage of fluentWait in your case be the following:

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

这种方法更好,因为你不知道确切的等待时间和轮询时间间隔你可以设置任意时间值,通过验证元素存在。
问候。

This approach IMHO better as you do not know exactly how much time to wait and in polling interval you can set arbitrary timevalue which element presence will be verified through . Regards.

这篇关于如何让Selenium-WebDriver在Java中等待几秒钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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