c# - ExecuteScript 上的 Selenium 超时

标签 c# .net selenium selenium-webdriver timeout

无论我尝试做什么来避免它们,在使用 Selenium 执行脚本时我都会超时。

我首先将超时设置得长得离谱:

_driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromMinutes(30));               
_driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(30));

稍后,我运行了一个预计需要很长时间的脚本(它正在执行一个长时间运行的 POST 请求)。无论我使用 ExecuteScript 还是 ExecuteAsyncScript,请求都会在 60 秒时超时。

我能做些什么来避免这种情况吗?在这一点上,即使是 hack 或解决方法也会很好。

最佳答案

与驱动程序的连接有 60 秒超时。更改它的方法是编辑 protected 字段 RemoteWebDriver.DefaultCommandTimeout:

typeof(RemoteWebDriver)
    .GetField("DefaultCommandTimeout", BindingFlags.NonPublic | BindingFlags.Static)
    .SetValue(null, TimeSpan.FromMinutes(5));

另一种方法是在请求返回后设置一个变量,然后等待它:

((IJavaScriptExecutor)driver).ExecuteScript(@"
    window._result = null;
    var req = new XMLHttpRequest();
    req.onreadystatechange = function(){
        if(req.readyState == XMLHttpRequest.DONE) {
            window._result = this.responseText);
        }
    };
    req.open('GET', '...');
    req.send();
");

var response = new WebDriverWait(driver, TimeSpan.FromMinutes(5))
    .Until(_ => ((IJavaScriptExecutor)_).ExecuteScript("return window._result;"));

关于c# - ExecuteScript 上的 Selenium 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905913/

相关文章:

.net - 在 Visual Studio 中调试时如何更改工作目录?

c# - JWT最快算法

java - org.openqa.selenium.WebDriverException : java.net.ConnectException:无法使用 GeckoDriver Firefox 和 Selenium 连接到 localhost/0:0:0:0:0:0:0

c# - 可空属性的映射结果为 0 但不是 Null

c# - 何时使用 Process.EnterDebugMode

c# - C#XML注释中的尖括号

java - 在没有浏览器焦点的情况下执行基于 WebDriver 的测试

javascript - 如何使用 setAttribute 方法和 Python 中的 Selenium 更改 Datepicker 的隐藏元素的日期?

c# - DispatcherTimer 未在 wpf 应用程序中触发

c# - Excel Interop 获取单元格内文本的像素宽度