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

查看:23
本文介绍了如何让 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 秒的隐式等待.但我无法找到元素文本框

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

你可以在细节上有所不同此处.

You can get difference in details here.

在这种情况下,我更喜欢使用显式等待(特别是 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 函数返回您找到的 Web 元素.来自 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 的用法如下:

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天全站免登陆