无论我尝试做什么来避免它们,在使用 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/