C# 模擬瀏覽器并自動操作的實例代碼
本文主要講解通過WebBrowser控件打開瀏覽頁面,并操作頁面元素實現自動搜索功能,僅供學習分享使用,如有不足之處,還請指正。
涉及知識點
- WebBrowser:用于在WinForm窗體中,模擬瀏覽器,打開并導航網頁。
- HtmlDocument:表示一個Html文檔的頁面。每次加載都會是一個全新的頁面。
- GetElementById(string id):通過ID或Name獲取一個Html中的元素。
- HtmlElement:表示一個Html標簽元素。
- BackgroundWorker 后臺執(zhí)行獨立操作的進程。
設計思路
主要采用異步等待的方式,等待頁面加載完成,流程如下所示:
示例效果圖
如下所示:加載完成后,自動輸入【天安門】并點擊搜索。
核心代碼
加載新的頁面,如下所示:
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()觸發(fā)事件。
示例核心代碼
如下所示:
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, 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# 模擬瀏覽器并自動操作的資料請關注腳本之家其它相關文章!
相關文章
在C#中使用OpenCV(使用OpenCVSharp)的實現
這篇文章主要介紹了在C#中使用OpenCV(使用OpenCVSharp)的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11C# CancellationToken和CancellationTokenSource的用法詳解
做了.net core之后,發(fā)現CancellationToken用的越來越平凡了。這也難怪,原來.net framework使用異步的不是很多,而.net core首推異步編程,到處可以看到Task的影子,而CancellationToken正好是異步Task的一個控制器,所以花點時間做個筆記2021-06-06