public void PortalLogin()
{
string portalUrl = "URL";
string portalEmail = "email";
string portalPassword = "password";
// Run when page finishes navigating
webBrowser2.DocumentCompleted += (s, e) =>
{
HtmlElement head = webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript = webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)testScript.DomElement;
element.text = "function PortalLogin() { document.getElementById('username').value = '" + portalEmail + "'; document.getElementById('password').value = '" + portalPassword + "'; document.getElementById('credentials').submit(); }";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("PortalLogin");
};
// Navigate to the portal
webBrowser2.Navigate(portalUrl);
while (this.webBrowser2.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
我上面的代码段应该Navigate
到特定的URL,然后在Navigate完成后,执行调用脚本登录到那里的网页。现在,因为整个PortalLogin()
函数都在while循环中,所以我必须包含:
while (this.webBrowser2.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
段,以便while循环不会中断导航功能。但是,代码不能正常工作,当我使用断点逐步执行时,流程似乎已关闭。我认为部分问题是我不太明白while循环测试ReadState != Complete
是如何工作的。有人可以启发我吗?
答案 0 :(得分:-2)
最好使用带有cookie或HttpWebRequest和HttpWebResponse的WebClient。