private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { //如果需要登录,调用自动登录的过程 //this.AutoLogon("帐号", "密码"); //取得目标页面的所有link, 然后分析这些 link, 找到需要点击的 HtmlElementCollection links = this.webBrowser1.Document.Links; foreach (HtmlElement link in links) { //我这里用 google 的链接,做示例 if (link.GetAttribute("href").Contains("google.com")) { link.InvokeMember("click"); //激发链接的点击事件 } } } /// <summary> /// 自动登录,适用于没有验证码的情况 /// </summary> /// <param name="userId">登录的帐号</param> /// <param name="password">登录的密码</param> private void AutoLogon(string userId, string password) { #region 获取登录FORM的输入框 和 Submit 按钮 HtmlElement textboxUserId = this.webBrowser1.Document.GetElementById("登录用户名文本框的ID"); //如果没有ID,用 Name 获取 //HtmlElement textboxUserId = this.webBrowser1.Document.All["登录用户名文本框的Name"]; HtmlElement textboxPassword = this.webBrowser1.Document.GetElementById("登录密码框的ID"); //如果没有ID, 用Name 获取 //HtmlElement textboxPassword = this.webBrowser1.Document.All["登录密码框的Name"]; HtmlElement buttonSubmit = this.webBrowser1.Document.GetElementById("登录按钮的ID"); //如果没有ID, 用Name获取 //HtmlElement buttonSubmit = this.webBrowser1.Document.All["登录按钮的Name"]; textboxUserId.SetAttribute("value", userId); //填写帐号 textboxPassword.SetAttribute("value", password); //填写密码 buttonSubmit.InvokeMember("click"); //触发提交按钮的点击事件 //当然,登录,也可以用 //this.webBrowser1.Document.Forms[0].InvokeMember("submit"); //来实现,但是,上面的语句,会跳过浏览器客户端验证函数(如果有的话) #endregion //登录后,需判断登录是否成功, 可以根据登录后的 URL //或者 this.webBrowser1.Document.Body.InnerHtml的内容来判断 }
浙公网安备 33010602011771号