【发布时间】:2020-02-29 15:29:36
【问题描述】:
我编写了一个 C# 扩展方法,它接受一个元素的 By 并尝试等待长达 5 秒,同时反复轮询页面以查看该元素是否存在。
代码如下:
public static IWebElement FindWithWait(this ISearchContext context, By by)
{
var wait = new DefaultWait<ISearchContext>(context)
{
Timeout = TimeSpan.FromSeconds(5)
};
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
return wait.Until(ctx =>
{
Console.WriteLine($"{DateTimeOffset.Now} wait is trying...");
return ctx.FindElement(by);
});
}
出于这个问题的目的,这是我调用该方法的方式:
Console.WriteLine($"{DateTimeOffset.Now} before");
try
{
var element = driver.FindWithWait(By.Id("not_in_page"));
}
catch (Exception ex)
{
Console.WriteLine($"{DateTimeOffset.Now} exception:" + ex);
}
Console.WriteLine($"{DateTimeOffset.Now} after");
鉴于页面中不存在 ID 为 #not_in_page 的元素,并且 Until() 方法的默认轮询时间为 500 毫秒,我希望代码打印出如下内容:
11/4/2019 11:20:00 AM +02:00 before
11/4/2019 11:20:00 AM +02:00 wait is trying...
11/4/2019 11:20:01 AM +02:00 wait is trying...
11/4/2019 11:20:01 AM +02:00 wait is trying...
11/4/2019 11:20:02 AM +02:00 wait is trying...
11/4/2019 11:20:02 AM +02:00 wait is trying...
11/4/2019 11:20:03 AM +02:00 wait is trying...
11/4/2019 11:20:03 AM +02:00 wait is trying...
11/4/2019 11:20:04 AM +02:00 wait is trying...
11/4/2019 11:20:04 AM +02:00 wait is trying...
11/4/2019 11:20:05 AM +02:00 wait is trying...
11/4/2019 11:20:05 AM +02:00 after
但是,我实际上得到的是:
11/4/2019 11:20:00 AM +02:00 before
11/4/2019 11:20:00 AM +02:00 wait is trying...
11/4/2019 11:21:00 AM +02:00 exception: OpenQA.Selenium.WebDriverException: The HTTP request to the remote WebDriver server for URL ######### timed out after 50 seconds. ---> #########
11/4/2019 11:21:00 AM +02:00 after
请注意,轮询似乎只发生一次,并且异常是在开始轮询后 60 秒引发的。
wait.Until() 是否会隐含等待 60 秒?我怎样才能让它忽略它并每 500 毫秒轮询一次?
【问题讨论】:
标签: .net selenium webdriverwait implicitwait