我正在尝试使用 .NET C# 自动化 Webbrowser。问题是控件或者我应该说 IE 浏览器在不同的计算机上表现得很奇怪。例如,我点击链接并在第一台计算机上填写一个 Ajax 弹出表单,如下所示,没有任何错误:
private void btn_Start_Click(object sender, RoutedEventArgs e)
{
webbrowserIE.Navigate("http://www.test.com/");
webbrowserIE.DocumentCompleted += fillup_LoadCompleted;
}
void fillup_LoadCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
System.Windows.Forms.HtmlElement ele = web_BrowserIE.Document.GetElementById("login");
if (ele != null)
ele.InvokeMember("Click");
if (this.web_BrowserIE.ReadyState == System.Windows.Forms.WebBrowserReadyState.Complete)
{
web_BrowserIE.Document.GetElementById("login").SetAttribute("value", myUserName);
web_BrowserIE.Document.GetElementById("password").SetAttribute("value", myPassword);
foreach (System.Windows.Forms.HtmlElement el in web_BrowserIE.Document.GetElementsByTagName("button"))
{
if (el.InnerText == "Login")
{
el.InvokeMember("click");
}
}
web_BrowserIE.DocumentCompleted -= fillup_LoadCompleted;
}
}
但是,上面的代码在第二台电脑上不起作用,唯一的点击方式是这样的:
private void btn_Start_Click(object sender, RoutedEventArgs e)
{
webbrowserIE.DocumentCompleted += click_LoadCompleted;
webbrowserIE.Navigate("http://www.test.com/");
}
void click_LoadCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
if (this.webbrowserIE.ReadyState == System.Windows.Forms.WebBrowserReadyState.Complete)
{
System.Windows.Forms.HtmlElement ele = webbrowserIE.Document.GetElementById("login");
if (ele != null)
ele.InvokeMember("Click");
webbrowserIE.DocumentCompleted -= click_LoadCompleted;
webbrowserIE.DocumentCompleted += fillup_LoadCompleted;
}
}
void click_LoadCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
webbrowserIE.Document.GetElementById("login_login").SetAttribute("value", myUserName);
webbrowserIE.Document.GetElementById("login_password").SetAttribute("value", myPassword);
//If you know the ID of the form you would like to submit:
foreach (System.Windows.Forms.HtmlElement el in webbrowserIE.Document.GetElementsByTagName("button"))
{
if (el.InnerText == "Login")
{
el.InvokeMember("click");
}
}
webbrowserIE.DocumentCompleted -= click_LoadCompleted;
}
因此,在第二个解决方案中,我必须调用两个 Load Completed Chains。有人可以建议我应该如何处理这个问题吗?此外,提出更稳健的方法的建议将非常有帮助。先感谢您