C# 模擬瀏覽器並自動操作的例項程式碼
阿新 • • 發佈:2020-07-10
本文主要講解通過WebBrowser控制元件開啟瀏覽頁面,並操作頁面元素實現自動搜尋功能,僅供學習分享使用,如有不足之處,還請指正。
涉及知識點
- WebBrowser:用於在WinForm窗體中,模擬瀏覽器,開啟並導航網頁。
- HtmlDocument:表示一個Html文件的頁面。每次載入都會是一個全新的頁面。
- GetElementById(string id):通過ID或Name獲取一個Html中的元素。
- HtmlElement:表示一個Html標籤元素。
- BackgroundWorker 後臺執行獨立操作的程序。
設計思路
主要採用非同步等待的方式,等待頁面載入完成,流程如下所示:
示例效果圖
如下所示:載入完成後,自動輸入【天安門】並點選搜尋。
核心程式碼
載入新的頁面,如下所示:
string url = "https://www.so.com/"; this.wb01.ScriptErrorsSuppressed = true; this.wb01.Navigate(url);
注意:this.wb01.ScriptErrorsSuppressed = true;用於是否彈出異常指令碼程式碼錯誤框
獲取元素並賦值,如下所示:
string search_id = "input"; string search_value = "天安門"; string btn_id = "search-button"; HtmlDocument doc = this.wb01.Document; HtmlElement search = doc.GetElementById(search_id); search.SetAttribute("value",search_value); HtmlElement btn = doc.GetElementById(btn_id); btn.InvokeMember("click");
示例整體程式碼,如下所示:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace DemoExplorer { public partial class FrmExplorer : Form { private bool isLoadOk = false; private BackgroundWorker bgWork; public FrmExplorer() { InitializeComponent(); } private void FrmExplorer_Load(object sender,EventArgs e) { bgWork = new BackgroundWorker(); bgWork.DoWork += bgWork_DoWork; bgWork.RunWorkerCompleted += bgWork_RunWorkerCompleted; string url = "https://www.so.com/"; this.wb01.ScriptErrorsSuppressed = true; this.wb01.Navigate(url); bgWork.RunWorkerAsync(); } private void bgWork_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) { string search_id = "input"; string search_value = "天安門"; string btn_id = "search-button"; HtmlDocument doc = this.wb01.Document; HtmlElement search = doc.GetElementById(search_id); search.SetAttribute("value",search_value); HtmlElement btn = doc.GetElementById(btn_id); btn.InvokeMember("click"); } private void bgWork_DoWork(object sender,DoWorkEventArgs e) { compWait(); } private void compWait() { while (!isLoadOk) { Thread.Sleep(500); } } private void wb01_DocumentCompleted(object sender,WebBrowserDocumentCompletedEventArgs e) { this.wb01.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error); if (this.wb01.ReadyState == WebBrowserReadyState.Complete) { isLoadOk = true; } else { isLoadOk = false; } } private void Window_Error(object sender,HtmlElementErrorEventArgs e) { e.Handled = true; } } }
另外一種實現方式(MSHTML)
什麼是MSHTML?
MSHTML是windows提供的用於操作IE瀏覽器的一個COM元件,該元件封裝了HTML語言中的所有元素及其屬性,通過其提供的標準介面,可以訪問指定網頁的所有元素。
涉及知識點
InternetExplorer 瀏覽器物件介面,其中DocumentComplete是文件載入完成事件。
HTMLDocumentClass Html文件物件類,用於獲取頁面元素。
IHTMLElement 獲取頁面元素,通過setAttribute設定屬性值,和click()觸發事件。
示例核心程式碼
如下所示:
namespace AutoGas { public class Program { private static bool isLoad = false; public static void Main(string[] args) { string logUrl = ConfigurationManager.AppSettings["logUrl"]; //登入Url string uid = ConfigurationManager.AppSettings["uid"];//使用者名稱ID string pid = ConfigurationManager.AppSettings["pid"];//密碼ID string btnid = ConfigurationManager.AppSettings["btnid"];//按鈕ID string uvalue = ConfigurationManager.AppSettings["uvalue"];//使用者名稱 string pvalue = ConfigurationManager.AppSettings["pvalue"];//密碼 InternetExplorer ie = new InternetExplorerClass(); ie.DocumentComplete += Ie_DocumentComplete; object c = null; ie.Visible = true; ie.Navigate(logUrl,ref c,ref c); ie.FullScreen = true; compWait(); try { HTMLDocumentClass doc = (HTMLDocumentClass)ie.Document; IHTMLElement username = doc.getElementById(uid); IHTMLElement password = doc.getElementById(pid); IHTMLElement btn = doc.getElementById(btnid); //如果有session,則自動登入,不需要輸入賬號密碼 if (username != null && password != null && btn != null) { username.setAttribute("value",uvalue); password.setAttribute("value",pvalue); btn.click(); } } catch (Exception ex) { } } public static void compWait() { while (!isLoad) { Thread.Sleep(200); } } /// <summary> /// /// </summary> /// <param name="pDisp"></param> /// <param name="URL"></param> private static void Ie_DocumentComplete(object pDisp,ref object URL) { isLoad = true; } } }
以上就是C# 模擬瀏覽器並自動操作的例項程式碼的詳細內容,更多關於C# 模擬瀏覽器並自動操作的資料請關注我們其它相關文章!