本文主要講解通過WebBrowser控制項打開頁面,並自動輸入實現搜索功能,僅供學習分享使用,如有不足之處,還請指正。 ...
本文主要講解通過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 }View Code
備註
所謂的堅持,不過是每天努力一點點!!!