为什么我的显式等待在Selenium .Net中不起作用?

我编写了一个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毫秒轮询一次?

zilan112 回答:为什么我的显式等待在Selenium .Net中不起作用?

哦,兄弟。提交问题后,我意识到发生了什么事。

waiting...消息仅打印一次以及60秒后引发异常的原因是,在我的代码的较早位置,隐式等待被设置为60秒。删除该代码后,代码按预期运行。

按预期每500毫秒进行一次显式等待轮询的解决方案是永远不要为使用的驱动程序设置隐式等待。

另一种方法太讨厌我了:我可以尝试在扩展方法的开头捕获隐式等待值,然后将其设置为0并进行轮询,最后将其重置为捕获的值。

底线-混合使用隐式等待和显式等待来等待给定的驱动程序实例是一个坏主意。

本文链接:https://www.f2er.com/3167587.html

大家都在问