0
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 循环不会仅仅中断 Navigate 函数。但是,代码不是很有效,当我用断点单步执行它时,流程似乎已经关闭。我认为部分问题是我不太了解 while 循环测试的ReadState != Complete工作原理。有人可以启发我吗?

4

1 回答 1

-2

最好将 WebClient 与 cookie 或 HttpWebRequest 和 HttpWebResponse 一起使用。

于 2013-08-19T17:03:34.413 回答