0

I've written a C# extension method that accepts a By for an element and tries to wait for up to 5 seconds while repeatedly polling the page to see if the element is present.

Here's the code:

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

For the purpose of this question, here's how I invoke the method:

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

Given that an element with id #not_in_page does not exist in the page and that the default polling time for the Until() method is 500 milliseconds, I would expect the code to print out something like:

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

However, what I'm actually getting is :

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

Note that the polling seems to happen only once and that the exception was thrown 60 seconds after starting to poll.

Is wait.Until() subject to an implicit wait of 60 seconds? How can I instead make it ignore it and poll once every 500 milliseconds?

4

1 回答 1

0

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

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

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

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

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

于 2019-11-04T10:49:31.627 回答