C#模拟浏览器并⾃动操作的实例代码
本⽂主要讲解通过WebBrowser控件打开浏览页⾯,并操作页⾯元素实现⾃动搜索功能,仅供学习分享使⽤,如有不⾜之处,还请指正。
涉及知识点
1. WebBrowser:⽤于在WinForm窗体中,模拟浏览器,打开并导航⽹页。
2. HtmlDocument:表⽰⼀个Html⽂档的页⾯。每次加载都会是⼀个全新的页⾯。
3. GetElementById(string id):通过ID或Name获取⼀个Html中的元素。
4. HtmlElement:表⽰⼀个Html标签元素。
5. BackgroundWorker 后台执⾏独⽴操作的进程。
设计思路
主要采⽤异步等待的⽅式,等待页⾯加载完成,流程如下所⽰:
⽰例效果图
如下所⽰:加载完成后,⾃动输⼊【天安门】并点击搜索。
核⼼代码
加载新的页⾯,如下所⽰:
string url = "www.so/";
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 = "www.so/";
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;
}
}
html document是什么
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, ref c, ref c);
ie.FullScreen = true;
compWait();
try
{
HTMLDocumentClass doc = (HTMLDocumentClass)ie.Document;
IHTMLElement username = ElementById(uid);
IHTMLElement password = ElementById(pid);
IHTMLElement btn = ElementById(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# 模拟浏览器并⾃动操作的资料请关注其它相关⽂章!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。