C# 模擬瀏覽器并自動操作的實(shí)例代碼
本文主要講解通過WebBrowser控件打開瀏覽頁面,并操作頁面元素實(shí)現(xiàn)自動搜索功能,僅供學(xué)習(xí)分享使用,如有不足之處,還請指正。
涉及知識點(diǎn)
- WebBrowser:用于在WinForm窗體中,模擬瀏覽器,打開并導(dǎo)航網(wǎng)頁。
- HtmlDocument:表示一個(gè)Html文檔的頁面。每次加載都會是一個(gè)全新的頁面。
- GetElementById(string id):通過ID或Name獲取一個(gè)Html中的元素。
- HtmlElement:表示一個(gè)Html標(biāo)簽元素。
- BackgroundWorker 后臺執(zhí)行獨(dú)立操作的進(jìn)程。
設(shè)計(jì)思路
主要采用異步等待的方式,等待頁面加載完成,流程如下所示:

示例效果圖
如下所示:加載完成后,自動輸入【天安門】并點(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)頁的所有元素。
涉及知識點(diǎn)
InternetExplorer 瀏覽器對象接口,其中DocumentComplete是文檔加載完成事件。
HTMLDocumentClass Html文檔對象類,用于獲取頁面元素。
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,則自動登錄,不需要輸入賬號密碼
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# 模擬瀏覽器并自動操作的實(shí)例代碼的詳細(xì)內(nèi)容,更多關(guān)于C# 模擬瀏覽器并自動操作的資料請關(guān)注腳本之家其它相關(guān)文章!
- C#實(shí)現(xiàn)清除IE瀏覽器緩存的方法
- C#實(shí)現(xiàn)基于IE內(nèi)核的簡單瀏覽器完整實(shí)例
- C# 利用Selenium實(shí)現(xiàn)瀏覽器自動化操作的示例代碼
- 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)簡易圖片瀏覽器的方法
- C#使用默認(rèn)瀏覽器打開網(wǎng)頁的方法
- c# 從IE瀏覽器獲取當(dāng)前頁面的內(nèi)容
相關(guān)文章
C#使用表達(dá)式樹(LambdaExpression)動態(tài)更新類的屬性值(示例代碼)
這篇文章主要介紹了C#使用表達(dá)式樹(LambdaExpression)動態(tài)更新類的屬性值,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01
C#實(shí)現(xiàn)日期時(shí)間的格式化輸出的示例詳解
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)日期時(shí)間的格式化輸出的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以參考一下2023-03-03
C#利用Refit實(shí)現(xiàn)JWT自動續(xù)期詳解
Refit?是一個(gè)受到Square的Retrofit庫(Java)啟發(fā)的自動類型安全REST庫,這篇文章主要為大家介紹了C#如何利用Refit實(shí)現(xiàn)JWT自動續(xù)期,感興趣的可以了解下2023-08-08

