在下面的代碼中,我使用linkcount來控制事件發生的時間。問題是,linkcount == 3在linkcount == 2完成並且發生錯誤之前正在運行。第三部分是在頁面加載之前在網頁上查找元素。如何更好地控制代碼中的事件序列?
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
linkcount++;
if (linkcount == 1)
{
webBrowser1.Document.GetElementById("ctl00_Content_Login1_UserName").SetAttribute("value", "username");
webBrowser1.Document.GetElementById("ctl00_Content_Login1_Password").SetAttribute("value", "password");
webBrowser1.Document.GetElementById("ctl00_Content_Login1_LoginButton").InvokeMember("click");
}
if (linkcount == 2)
{
HtmlElement link = (from HtmlElement elem in webBrowser1.Document.GetElementsByTagName("a")
where elem.InnerHtml == "Time Clock Entry"
select elem).ElementAt(0);
link.InvokeMember("Click");
}
if (linkcount == 3)
{
webBrowser1.Document.Window.Frames["ContentFrame"].Document.GetElementById("btnPunch").InvokeMember("Click");
// string content = webBrowser1.Document.Window.Frames[0].WindowFrameElement.InnerText;
// string content = webBrowser1.Document.Window.Frames[0].Document.Body.InnerText;
// MessageBox.Show(content);
// link.InvokeMember("Click");
}
}
檢查'GetElementById'的返回值。如果它是'null',那麼該元素不可用。 –
難道你沒有辦法通過閱讀'webBrowser1.Document'的某個屬性來確定你在哪個步驟?例如,如果文檔包含某些特定的文本,那麼您100%確定您處於三種情況之一。 –