C# 模擬瀏覽器并自動(dòng)操作的實(shí)例代碼
本文主要講解通過WebBrowser控件打開瀏覽頁面,并操作頁面元素實(shí)現(xiàn)自動(dòng)搜索功能,僅供學(xué)習(xí)分享使用,如有不足之處,還請(qǐng)指正。
涉及知識(shí)點(diǎn)
- WebBrowser:用于在WinForm窗體中,模擬瀏覽器,打開并導(dǎo)航網(wǎng)頁。
- HtmlDocument:表示一個(gè)Html文檔的頁面。每次加載都會(huì)是一個(gè)全新的頁面。
- GetElementById(string id):通過ID或Name獲取一個(gè)Html中的元素。
- HtmlElement:表示一個(gè)Html標(biāo)簽元素。
- BackgroundWorker 后臺(tái)執(zhí)行獨(dú)立操作的進(jìn)程。
設(shè)計(jì)思路
主要采用異步等待的方式,等待頁面加載完成,流程如下所示:
示例效果圖
如下所示:加載完成后,自動(dòng)輸入【天安門】并點(diǎn)擊搜索。
核心代碼
加載新的頁面,如下所示:
string url = "https://www.so.com/"; this.wb01.ScriptErrorsSuppressed = true; this.wb01.Navigate(url);
注意:this.wb01.ScriptErrorsSuppressed = true;用于是否彈出異常腳本代碼錯(cuò)誤框
獲取元素并賦值,如下所示:
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; } } }
另外一種實(shí)現(xiàn)方式(MSHTML)
什么是MSHTML?
MSHTML是windows提供的用于操作IE瀏覽器的一個(gè)COM組件,該組件封裝了HTML語言中的所有元素及其屬性,通過其提供的標(biāo)準(zhǔn)接口,可以訪問指定網(wǎng)頁的所有元素。
涉及知識(shí)點(diǎn)
InternetExplorer 瀏覽器對(duì)象接口,其中DocumentComplete是文檔加載完成事件。
HTMLDocumentClass Html文檔對(duì)象類,用于獲取頁面元素。
IHTMLElement 獲取頁面元素,通過setAttribute設(shè)置屬性值,和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,則自動(dòng)登錄,不需要輸入賬號(hào)密碼 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# 模擬瀏覽器并自動(dòng)操作的實(shí)例代碼的詳細(xì)內(nèi)容,更多關(guān)于C# 模擬瀏覽器并自動(dòng)操作的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- C#實(shí)現(xiàn)清除IE瀏覽器緩存的方法
- C#實(shí)現(xiàn)基于IE內(nèi)核的簡(jiǎn)單瀏覽器完整實(shí)例
- C# 利用Selenium實(shí)現(xiàn)瀏覽器自動(dòng)化操作的示例代碼
- C#瀏覽器提示跨域問題解決方案
- C#導(dǎo)出pdf的實(shí)現(xiàn)方法(瀏覽器不預(yù)覽直接下載)
- C# WinForm實(shí)現(xiàn)圖片瀏覽器
- C#文件下載實(shí)例代碼(適用于各個(gè)瀏覽器)
- C#實(shí)現(xiàn)多選項(xiàng)卡的瀏覽器控件
- C#編程實(shí)現(xiàn)簡(jiǎn)易圖片瀏覽器的方法
- C#使用默認(rèn)瀏覽器打開網(wǎng)頁的方法
- c# 從IE瀏覽器獲取當(dāng)前頁面的內(nèi)容
相關(guān)文章
C#實(shí)現(xiàn)WPS文件轉(zhuǎn)PDF格式的方法示例
這篇文章主要介紹了C#實(shí)現(xiàn)WPS文件轉(zhuǎn)PDF格式的方法,涉及C#針對(duì)office組件的相關(guān)引用與操作技巧,需要的朋友可以參考下2017-11-11C#實(shí)現(xiàn)簡(jiǎn)單的Login窗口實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)簡(jiǎn)單的Login窗口,實(shí)例分析了C#顯示及關(guān)閉登陸Login窗口的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-08-08在C#中使用OpenCV(使用OpenCVSharp)的實(shí)現(xiàn)
這篇文章主要介紹了在C#中使用OpenCV(使用OpenCVSharp)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11C# CancellationToken和CancellationTokenSource的用法詳解
做了.net core之后,發(fā)現(xiàn)CancellationToken用的越來越平凡了。這也難怪,原來.net framework使用異步的不是很多,而.net core首推異步編程,到處可以看到Task的影子,而CancellationToken正好是異步Task的一個(gè)控制器,所以花點(diǎn)時(shí)間做個(gè)筆記2021-06-06C# 實(shí)現(xiàn)簡(jiǎn)易的串口監(jiān)視上位機(jī)功能附源碼下載
這篇文章主要介紹了C# 實(shí)現(xiàn)簡(jiǎn)易的串口監(jiān)視上位機(jī)功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11C#.Net基于正則表達(dá)式抓取百度百家文章列表的方法示例
這篇文章主要介紹了C#.Net基于正則表達(dá)式抓取百度百家文章列表的方法,結(jié)合實(shí)例形式分析了C#獲取百度百家文章內(nèi)容及使用正則表達(dá)式匹配標(biāo)題、內(nèi)容、地址等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08利用C#/VB.NET實(shí)現(xiàn)PPT轉(zhuǎn)換為HTML
利用PowerPoint可以很方便的呈現(xiàn)多媒體信息,且信息形式多媒體化,表現(xiàn)力強(qiáng)。但難免在某些情況下我們會(huì)需要將PowerPoint轉(zhuǎn)換為HTML格式,本文就為大家整理了轉(zhuǎn)換方法,希望對(duì)大家有所幫助2023-05-05