如何在 Selenium 中结合隐式和显式超时? [英] How to combine implicit and explicit timeouts in Selenium?

查看:34
本文介绍了如何在 Selenium 中结合隐式和显式超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有隐式超时的 Selenium ChromeDriver:

I am using Selenium ChromeDriver with an implicit timeout:

_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);

在我的一项测试中,我想用显式超时覆盖它.在读取属性之前,我明确地等待元素被找到:

In one of my tests I want to override this with an explicit timeout. Before reading a property I explicitely wait for the element to be found:

WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(120));
wait.Until(d => d.FindElement(By.CssSelector("div.example")));

我预计这需要 120 秒才能尝试找到元素,但它在 5 秒后就超时了.

I would expect this to take 120s to try to find the element, but it times out after just 5 seconds.

推荐答案

根据 显式和隐式等待 明确提到:

不要混合隐式显式等待.这样做会导致不可预测的等待时间.例如,设置隐式等待 10 秒和显式等待 15 秒,可能会导致在 20 秒后超时.

Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.

如果您将隐式超时定义为:

_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);

在为要找到的元素引入显式等待之前,您需要删除隐式超时,如下所示:

Before inducing explicit wait for the element to be found you need to remove the implicit timeout as follows:

_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0);
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(120));
wait.Until(d => d.FindElement(By.CssSelector("div.example")));

完成显式等待后,您可以重新配置回隐式超时:

Once you are done with the explicit wait, you can re-configure back the implicit timeout again as:

_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0);
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(120));
wait.Until(d => d.FindElement(By.CssSelector("div.example")));
//perform your action with the element
_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);

这篇关于如何在 Selenium 中结合隐式和显式超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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