我编写了一个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毫秒,我希望代码可以打印出以下内容: / p>
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毫秒轮询一次?