【发布时间】:2015-01-09 09:10:26
【问题描述】:
我正在尝试使用 Selenium 捕捉 load(不是 onload)事件。
我的代码如下所示(参见 cmets):
// d is my webdriver
// go to url
d.Navigate().GoToUrl(url);
WebDriverWait wait = new WebDriverWait(d, TimeSpan.FromSeconds(30));
// create a function that add an element with id="my_123456789"
string javascript =
"my_readyFCT = function(){"
+ "alert('READY');"
+ "var e = document.createElement('div');"
+ "e.id = 'my_123456789';"
+ "document.body.appendChild(e);"
+ "};"
// call the function once 'load' event is fired
+ "window.addEventListener('load', my_readyFCT, false);"
((IJavaScriptExecutor)d).ExecuteScript(javascript);
// Selenium wait until the element with id "my_123456789" exists
wait.Until<IWebElement>(ExpectedConditions.ElementExists(By.Id("my_123456789")));
我总是遇到超时异常(30 秒),我看不出我做错了什么。
有什么想法吗?
注意:我尝试自己执行函数my_readyFCT,它创建了插入DOM的具有正确ID的元素。
编辑
这里是javascript:
my_readyFCT = function() {
alert('READY');
var e = document.createElement('div');
e.id = 'my_123456789';
document.body.appendChild(e);
};
// call the function once 'load' event is fired
window.addEventListener('load', my_readyFCT, false);
编辑 2
我必须说我找到了一种方法来避免GoToUrl 的常见行为(这是页面加载的方式):
var fb = new FirefoxBinary();
fb.Timeout = TimeSpan.FromMinutes(4);
FirefoxProfile fp = new FirefoxProfile();
// 'unstable' allow us to avoid the implicit wait in GoToUrl
fp.SetPreference("webdriver.load.strategy", "unstable");
d = new FirefoxDriver(fb, fp, TimeSpan.FromMinutes(1));
当我想更改网址时:
d.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(0));
try {
d.Navigate().GoToUrl(url);
}
catch(WebDriverException) /* will be thrown everytime */
{ }
WebDriverWait wait = new WebDriverWait(d, TimeSpan.FromSeconds(30));
/*
* ...
* ETC. See code above
* ...
*/
【问题讨论】:
标签: javascript c# .net selenium