本文主要讲解通过WebBrowser控件打开浏览页面,并操作页面元素实现自动搜索功能,仅供学习分享使用,如有不足之处,还请指正。
涉及知识点
- WebBrowser:用于在WinForm窗体中,模拟浏览器,打开并导航网页。
- HtmlDocument:表示一个Html文档的页面。每次加载都会是一个全新的页面。
- GetElementById(string id):通过ID或Name获取一个Html中的元素。
- HtmlElement:表示一个Html标签元素。
- BackgroundWorker 后台执行独立操作的进程。
设计思路
主要采用异步等待的方式,等待页面加载完成,流程如下所示:
示例效果图
如下所示:加载完成后,自动输入【天安门】并点击搜索。
核心代码
加载新的页面,如下所示:
1 string url = "https://www.so.com/"; 2 this.wb01.ScriptErrorsSuppressed = true; 3 this.wb01.Navigate(url);
注意:this.wb01.ScriptErrorsSuppressed = true;用于是否弹出异常脚本代码错误框
获取元素并赋值,如下所示:
1 string search_id = "input"; 2 string search_value = "天安门"; 3 string btn_id = "search-button"; 4 HtmlDocument doc = this.wb01.Document; 5 HtmlElement search = doc.GetElementById(search_id); 6 search.SetAttribute("value", search_value); 7 HtmlElement btn = doc.GetElementById(btn_id); 8 btn.InvokeMember("click");
示例整体代码,如下所示:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading; 9 using System.Threading.Tasks; 10 using System.Windows.Forms; 11 12 namespace DemoExplorer 13 { 14 public partial class FrmExplorer : Form 15 { 16 private bool isLoadOk = false; 17 18 private BackgroundWorker bgWork; 19 20 public FrmExplorer() 21 { 22 InitializeComponent(); 23 } 24 25 private void FrmExplorer_Load(object sender, EventArgs e) 26 { 27 bgWork = new BackgroundWorker(); 28 bgWork.DoWork += bgWork_DoWork; 29 bgWork.RunWorkerCompleted += bgWork_RunWorkerCompleted; 30 string url = "https://www.so.com/"; 31 this.wb01.ScriptErrorsSuppressed = true; 32 this.wb01.Navigate(url); 33 bgWork.RunWorkerAsync(); 34 } 35 36 private void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 37 { 38 string search_id = "input"; 39 string search_value = "天安门"; 40 string btn_id = "search-button"; 41 HtmlDocument doc = this.wb01.Document; 42 HtmlElement search = doc.GetElementById(search_id); 43 search.SetAttribute("value", search_value); 44 HtmlElement btn = doc.GetElementById(btn_id); 45 btn.InvokeMember("click"); 46 } 47 48 private void bgWork_DoWork(object sender, DoWorkEventArgs e) 49 { 50 compWait(); 51 } 52 53 private void compWait() 54 { 55 while (!isLoadOk) 56 { 57 Thread.Sleep(500); 58 } 59 } 60 61 private void wb01_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 62 { 63 this.wb01.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error); 64 if (this.wb01.ReadyState == WebBrowserReadyState.Complete) 65 { 66 isLoadOk = true; 67 } 68 else 69 { 70 isLoadOk = false; 71 } 72 } 73 74 private void Window_Error(object sender, HtmlElementErrorEventArgs e) 75 { 76 e.Handled = true; 77 } 78 } 79 }
备注
所谓的坚持,不过是每天努力一点点!!!
原文地址:https://www.cnblogs.com/hsiang/p/12070950.html
时间: 2024-10-29 19:11:29