C# Selenium WebDriver 偶尔抛出超时异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15268255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:11:39  来源:igfitidea点击:

Selenium WebDriver throws Timeout exceptions sporadically

c#.nettestingseleniumwebdriver

提问by dasheddot

Using selenium for ui tests on our project. We are running the newest version 2.30.0. We use Firefox WebDriver and are running Firefox 19.0.

在我们的项目中使用 selenium 进行 ui 测试。我们正在运行最新版本 2.30.0。我们使用 Firefox WebDriver 并运行 Firefox 19.0。

Generally said the ui test works local and even server side when I run the ui test in Visual Studio. Our ui tests gets executed nighlty on our build server. It uses the same deploy on the same server I test manually via Visual Studio.

当我在 Visual Studio 中运行 ui 测试时,通常说 ui 测试在本地甚至服务器端工作。我们的 ui 测试在我们的构建服务器上执行。它在我通过 Visual Studio 手动测试的同一台服务器上使用相同的部署。

But sporadically we run into following issue when the ui test gets executed on buildserver:

但是,当在 buildserver 上执行 ui 测试时,我们偶尔会遇到以下问题:

Test(s) failed. OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:7056/hub/session/bed1d0e7-efdc-46b6-ba07-34903519c44d/element/%7B8717bb19-96c7-44d3-b0ee-d4b989ae652d%7D/click timed out after 60 seconds.
      ----> System.Net.WebException : The operation has timed out
       at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
       at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
--WebException
   at System.Net.HttpWebRequest.GetResponse()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)

Basically the test clicks on an upload button where the input field was filled with a file before. Since the file is very small this gets done in a few seconds. Nevertheless the timout of 60 seconds is reached sometimes.

基本上,测试点击一个上传按钮,其中输入字段之前填充了一个文件。由于文件非常小,这可以在几秒钟内完成。不过有时会达到 60 秒的超时。

Any ideas how to isolate the underlying issue? Or run anybody into the same issue before? Any hints appreciated. Thanks.

任何想法如何隔离潜在问题?或者之前有人遇到过同样的问题?任何提示表示赞赏。谢谢。

回答by Iwan1993

In my case the page is simply not fully loaded. Some facebook plugin seems to load too long. I tried catching the exception and manipulating the uncomplete dom, but this didn't give me any results. :(

在我的情况下,页面根本没有完全加载。某些 facebook 插件似乎加载时间过长。我尝试捕获异常并操纵不完整的 dom,但这并没有给我任何结果。:(

John

约翰

回答by Infant Dev

We faced a similar issue on our project. The problem had nothing to do with Selenium or our app. It was timing out because the build server config for that project was supposed to timeout in 5 minutes. But all our tests were not getting completed in 5 minutes, hence the build was failing due to timeout issues randomly.

我们在项目中遇到了类似的问题。问题与 Selenium 或我们的应用程序无关。超时是因为该项目的构建服务器配置应该在 5 分钟内超时。但是我们所有的测试都没有在 5 分钟内完成,因此构建由于随机超时问题而失败。

Also we had a problem with firefox-19, the tests used to fail randomly. Somehow, firefox-10 only worked for our selenium tests.

我们也遇到了 firefox-19 的问题,这些测试曾经随机失败。不知何故,firefox-10 只适用于我们的硒测试。

回答by 9ikhan

Try this code:

试试这个代码:

  DesiredCapabilities caps = DesiredCapabilities.Firefox();   

 //set the timeout to 120 seconds
 IWebDriver driver = new RemoteWebDriver(new Uri("<app_url>"), caps, TimeSpan.FromSeconds(120));

回答by acarlon

I got this same error: .NET WebDriver: 2.37, FF: 25.0.1. I noticed that Firefox was locking up until I exited my test application, so I built the debug version of Firefox and found that the lock-up happened when it was writing to stderr. This gave me the clue to change the webdriver code so that it no longer redirects standard out and error and this solved my problem. It seems like the WebDriver is blocking the std error in some way. From MSDN:

我遇到了同样的错误:.NET WebDriver: 2.37, FF: 25.0.1。我注意到 Firefox 在退出测试应用程序之前一直处于锁定状态,因此我构建了 Firefox 的调试版本,发现在写入 stderr 时发生了锁定。这给了我更改 webdriver 代码的线索,以便它不再重定向标准输出和错误,这解决了我的问题。似乎 WebDriver 以某种方式阻止了 std 错误。来自 MSDN:

Synchronous read operations introduce a dependency between the caller reading from the StandardError stream and the child process writing to that stream. These dependencies can cause deadlock conditions...

同步读取操作在调用者从 StandardError 流读取和子进程写入该流之间引入了依赖关系。这些依赖关系可能导致死锁条件...

More info here.

更多信息在这里

For anyone wanting to make the same tweak I did: -

对于任何想要进行我所做的相同调整的人:-

  1. Get the Selenium source. Then check out the same code branch that you are using.

  2. In FireFoxBinary.cs:

    i. Wherever you find RedirectStandardError = true, change to RedirectStandardError = false.

    ii. Wherever you find RedirectStandardOutput = true, change to RedirectStandardOutput = false. (for non-Windows, there is also one in Executable.cs)

    iii. In ConsoleOuput, change 'return this.stream.ReadToEnd()', to 'return ""'

  3. Build and replace WebDriver.dll with yours.

  1. 获取硒源。然后检查您正在使用的相同代码分支。

  2. 在 FireFoxBinary.cs 中:

    一世。无论您在哪里找到RedirectStandardError = true,请更改为RedirectStandardError = false

    ii. 无论您在哪里找到RedirectStandardOutput = true,请更改为RedirectStandardOutput = false。(对于非 Windows,Executable.cs 中也有)

    三、在 ConsoleOuput 中,将 'return this.stream.ReadToEnd()' 更改为 'return ""'

  3. 用你的构建和替换 WebDriver.dll。

Disclaimer: This worked for me, but your issue might be different. Also as far as I can tell, this has no adverse effects other than disabling the console output, but there may be other side effects that I am unaware of.

免责声明:这对我有用,但您的问题可能有所不同。此外,据我所知,除了禁用控制台输出之外,这没有任何不利影响,但可能还有其他我不知道的副作用。

I would be interested to know if anyone else finds the same.

我很想知道是否有其他人发现相同的情况。

Since I have solved my problem, I will not dig any deeper. If anyone a Selenium group member wants more info / logs / tweaks I would be happy to do so.

既然我已经解决了我的问题,我不会再深入挖掘了。如果 Selenium 组成员想要更多信息/日志/调整,我很乐意这样做。

Hopefully this will get fixed soon.

希望这会很快得到解决。

Update

更新

It appears that Firefox v25 is not currently supported. See this comment.

目前似乎不支持 Firefox v25。看到这个评论

Update 25th Feb 2014

2014 年 2 月 25 日更新

See this update:

请参阅此更新

Okay, this issue in general does not manifest itself in IE, or so it seems from the comments. I'd like people to try with Firefox and Chrome, and the .NET bindings 2.40.0 (will be the next release at the time of this writing) or later, and see if this is still happening.

I've seen fewer reports of this happening in Chrome since 2.35.0, so I need to know if this is still an issue with the .NET bindings and a recent chromedriver.exe.

2.40.0 may have a fix for at least one of the issues that may cause this in Firefox.

好的,这个问题一般不会在 IE 中表现出来,或者从评论中看起来是这样。我希望人们尝试使用 Firefox 和 Chrome 以及 .NET 绑定 2.40.0(将是撰写本文时的下一个版本)或更高版本,看看是否仍然存在这种情况。

自 2.35.0 以来,我在 Chrome 中看到这种情况的报告较少,所以我需要知道这是否仍然是 .NET 绑定和最近的 chromedriver.exe 的问题。

2.40.0 可能至少修复了可能在 Firefox 中导致此问题的问题之一。

This solved the problem for me. Looking at the change log, there is a commit from 1/31/2014 to remove console logging redirection:

这为我解决了这个问题。查看更改日志,从 2014 年 1 月 31 日开始提交删除控制台日志重定向:

"No longer redirecting console output for Firefox in .NET bindings."

Which is the workaround I used here. So, it all makes sense.

这是我在这里使用的解决方法。所以,这一切都是有道理的。

回答by Nir

Happened to me in four different scenarios:

在四种不同的情况下发生在我身上:

  1. The cause was that the window handle I was querying was already closed or in closing stages. If this is the case, you better check that the window still exist before querying it. If you want to avoid the long timeout period of 60 seconds, you should change the way you create the Firefox instance to decrease the 60 seconds delay:

    new FirefoxDriver("FfBinaryPath", FfProfileInstance, TimeSpan.FromSeconds(5));

  2. The cause was the flash plugin 'Protected Mode'. This scenario happened to me only under windows 7 and 8 when they ran under Jenkins job, the timeout did not happened sporadically. In order to fix it, I ran my Firefox selenium instance with the flash security mode disabled:

    FfProfile.SetPreference("dom.ipc.plugins.flash.disable-protected-mode", true);

  3. Another cause, also non sporadic, under Jenkins and related to Flash, happened when using Firefox version 45. In order to resolve this issue I had to downgrade to version 44 or alteratively uninstall Flash.

  4. Internal browser reason: Sometimes the browser takes more than one minute to react Selenium calls. In such case, setting the browser command timeout above 60 seconds can solve the issue. for example:

    new FirefoxDriver("FfBinaryPath", FfProfileInstance, TimeSpan.FromMinutes(3));

  1. 原因是我查询的窗口句柄已经关闭或处于关闭阶段。如果是这种情况,您最好在查询之前检查该窗口是否仍然存在。如果您想避免 60 秒的长时间超时,您应该更改创建 Firefox 实例的方式以减少 60 秒延迟:

    new FirefoxDriver("FfBinaryPath", FfProfileInstance, TimeSpan.FromSeconds(5));

  2. 原因是 Flash 插件“保护模式”。当他们在 Jenkins 作业下运行时,这种情况仅在 Windows 7 和 8 下发生在我身上,超时不是偶然发生的。为了修复它,我在禁用 flash 安全模式的情况下运行了我的 Firefox selenium 实例:

    FfProfile.SetPreference("dom.ipc.plugins.flash.disable-protected-mode", true);

  3. 使用 Firefox 45 版时发生了另一个非偶发性的 Jenkins 下与 Flash 相关的原因。为了解决这个问题,我不得不降级到 44 版或另外卸载 Flash。

  4. 浏览器内部原因:有时浏览器需要一分钟以上才能响应 Selenium 调用。在这种情况下,将浏览器命令超时设置为 60 秒以上可以解决问题。例如:

    new FirefoxDriver("FfBinaryPath", FfProfileInstance, TimeSpan.FromMinutes(3));

回答by Dominik Lemberger

public static IWebElement WaitForElementVisible(By selector, uint timeout = Config.DefaultTimeoutSec)
    {
        IWebDriver driver = Browser.Instance.Driver;

        if (timeout > 0)
        {
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));

            wait.Until(ExpectedConditions.ElementIsVisible(selector));
            return driver.FindElement(selector);
        }
        else
        {
            // Search for element without timeout 
            return driver.FindElement(selector);
        }
    }

We use this to prevent such Element not found failures and it works like a charm.

我们用它来防止这种 Element not found 失败,它就像一个魅力。

There is also a different Version if the Element can be there, but doesn't have to be visible.

如果元素可以在那里,但不必是可见的,那么还有一个不同的版本。

Just use ExpectedConditions.ElementExists(selector)instead of ExpectedContitions.ElementIsVisible(selector)

只需使用ExpectedConditions.ElementExists(selector)代替ExpectedContitions.ElementIsVisible(selector)

edit: Browser.Instance.Driver is a class containing the instanced driver

编辑:Browser.Instance.Driver 是一个包含实例化驱动程序的类

回答by tanz

I had the same error with timing out. I was using the IEDriverServer (64bit) and on long sendKey commands it would timeout.

我有同样的超时错误。我正在使用 IEDriverServer(64 位)并且在很长的 sendKey 命令上它会超时。

The reason being is that the default timeout seems to be 60 seconds.

原因是默认超时似乎是 60 秒。

What fixed my issue is that I instantiated the driver with a method that enables you to enter in the location of the IEDriverServer, the options for the driver AND the timeout value.

解决我的问题是我使用一种方法实例化了驱动程序,该方法使您能够输入 IEDriverServer 的位置、驱动程序的选项和超时值。

Link to documentation : http://seleniumhq.github.io/selenium/docs/api/dotnet/

文档链接:http: //seleniumhq.github.io/selenium/docs/api/dotnet/

public InternetExplorerDriver(
    string internetExplorerDriverServerDirectory,
    InternetExplorerOptions options,
    TimeSpan commandTimeout
)

Parameters

参数

  1. InternetExplorerDriverServerDirectory:
    • Type : System.String
    • The full path to the directory containing IEDriverServer.exe
  2. options
    • Type : OpenQA.Selenium.IE.InternetExplorerOptions
    • The InternetExplorerOptions used to initialize the driver
  3. commandTimeout
    • Type : System.TimeSpan
    • The maximum amount of time to wait for each command
  1. InternetExplorerDriverServerDirectory:
    • 类型:System.String
    • 包含 IEDriverServer.exe 的目录的完整路径
  2. 选项
    • 类型:OpenQA.Selenium.IE.InternetExplorerOptions
    • 用于初始化驱动程序的 InternetExplorerOptions
  3. 命令超时
    • 类型:System.TimeSpan
    • 等待每个命令的最长时间

My code

我的代码

InternetExplorerOptions options = new InternetExplorerOptions();
        IWebDriver driver = new InternetExplorerDriver("C:/Users/jeff/AppData/Local/Microsoft/WindowsApps", options, TimeSpan.FromSeconds(120));

回答by Rain9333

I had the same issue as well but only on Firefox driver. Turns out it might be related to when you use the driver Navigate method and it tries to interact too fast with the page. Calling below code fix it for me on Navigate (I also recommend to use it before FindElement as well):

我也有同样的问题,但仅限于 Firefox 驱动程序。事实证明,这可能与您何时使用驱动程序 Navigate 方法有关,并且它试图与页面交互太快。在 Navigate 上调用下面的代码为我修复它(我也建议在 FindElement 之前使用它):

public void VerifyPageIsLoaded()
{
    var pageLoaded = false;

    for (var i = 0; i < DefaultTimeout.Timeout.Seconds; i++)
    {
        Thread.Sleep(1000);

        if (WebDriver.ExecuteJavaScript<string>("return document.readyState").Equals("complete"))
        //jQuery.active might cause problems on some browser or browserstack so I commented it out
        //&& WebDriver.ExecuteJavaScript<bool>("return jQuery.active == 0").Equals(true))
        {
            pageLoaded = true;
            break;
        }

        Thread.Sleep(1000);
    }

    if (!pageLoaded)
    {
        throw new Exception("Page was not with complete state)!");
    }
}