微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C# 模拟浏览器并自动操作

本文主要讲解通过Webbrowser控件打开浏览页面,并操作页面元素实现自动搜索功能,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

  1. Webbrowser:用于在WinForm窗体中,模拟浏览器,打开并导航网页。
  2. HtmlDocument:表示一个Html文档的页面。每次加载都会是一个全新的页面
  3. GetElementById(string id):通过ID或Name获取一个Html中的元素。
  4. HtmlElement:表示一个Html标签元素。
  5. BackgroundWorker 后台执行独立操作的进程。

设计思路

主要采用异步等待的方式,等待页面加载完成,流程如下所示:

示例效果

如下所示:加载完成后,自动输入【天安门】并点击搜索

核心代码

加载新的页面,如下所示:

1 string url = "https://www.so.com/";
2 this.wb01.ScriptErroRSSuppressed = true3 this.wb01.Navigate(url);

注意:this.wb01.ScriptErroRSSuppressed = true;用于是否弹出异常脚本代码错误

获取元素并赋值,如下所示:

string search_id = inputstring search_value = 天安门string btn_id = search-button4 HtmlDocument doc = this.wb01.Document;
5 HtmlElement search = doc.GetElementById(search_id);
6 search.SetAttribute(value,search_value);
7 HtmlElement btn = doc.GetElementById(btn_id);
8 btn.InvokeMember(click");

示例整体代码,如下所示:

 1 using System;
 2  System.Collections.Generic;
 3  System.ComponentModel;
 4  System.Data;
 5  System.Drawing;
 6  System.Linq;
 7  System.Text;
 8  System.Threading;
 9  System.Threading.Tasks;
10  System.Windows.Forms;
11 
12 namespace DemoExplorer
13 {
14     public partial class FrmExplorer : Form
15     {
16         private bool isLoadOk = false17 
18         private BackgroundWorker bgWork;
19 
20         public FrmExplorer()
21         {
22             InitializeComponent();
23         }
24 
25         void FrmExplorer_Load(object sender,EventArgs e)
26 27             bgWork = new BackgroundWorker();
28             bgWork.DoWork += bgWork_DoWork;
29             bgWork.RunWorkerCompleted += bgWork_RunWorkerCompleted;
30             31             32             .wb01.Navigate(url);
33             bgWork.RunWorkerAsync();
34 35 
36         void bgWork_RunWorkerCompleted(37 38             39             40             41             HtmlDocument doc = 42             HtmlElement search =43             search.SetAttribute(44             HtmlElement btn =45             btn.InvokeMember();
46 47 
48         void bgWork_DoWork(49 50             compWait();
51 52 
53         void compWait()
54 55             while (!isLoadOk)
56             {
57                 Thread.Sleep(50058             }
59 60 
61         void wb01_DocumentCompleted(browserDocumentCompletedEventArgs e)
62 63             this.wb01.Document.Window.Error +=  HtmlElementErrorEventHandler(Window_Error);
64             if (this.wb01.ReadyState == WebbrowserReadyState.Complete)
65 66                 isLoadOk = 67 68             else
69 70                 isLoadOk = 71 72 73 
74         void Window_Error(75 76             e.Handled = 77 78     }
79 }
View Code

 另外一种实现方式(MSHTML)

什么是MSHTML?

MSHTML是windows提供的用于操作IE浏览器的一个COM组件,该组件封装了HTML语言中的所有元素及其属性,通过其提供的标准接口,可以访问指定网页的所有元素。

涉及知识点

InternetExplorer 浏览器对象接口,其中DocumentComplete是文档加载完成事件。

HTMLDocumentClass Html文档对象类,用于获取页面元素。

IHTMLElement 获取页面元素,通过setAttribute设置属性值,和click()触发事件。

示例核心代码

如下所示:

 1 namespace AutoGas
 2 {
 3     public class Program
 4     {
 5         private static bool isLoad = false;
 6 
 7         void Main(string[] args)
 8         {
 9             string logUrl = ConfigurationManager.AppSettings["logUrl"]; //登录Url
10             string uid = ConfigurationManager.AppSettings[uid"];用户名ID
11             string pid = ConfigurationManager.AppSettings[pid密码ID
12             string btnid = ConfigurationManager.AppSettings[btnid按钮ID
13             string uvalue = ConfigurationManager.AppSettings[uvalue用户名
14             string pvalue = ConfigurationManager.AppSettings[pvalue密码
15             InternetExplorer ie = new InternetExplorerClass();
16             ie.DocumentComplete += Ie_DocumentComplete;
17             object c = null18             ie.Visible = true19             ie.Navigate(logUrl,ref c,1)">ref c);
20             ie.FullScreen = 21 
22             compWait();
23             try
24             {
25                 HTMLDocumentClass doc = (HTMLDocumentClass)ie.Document;
26                 IHTMLElement username = doc.getElementById(uid);
27                 IHTMLElement password = doc.getElementById(pid);
28                 IHTMLElement btn = doc.getElementById(btnid);
29                 如果有session,则自动登录,不需要输入账号密码
30                 if (username != null && password != null && btn != )
31                 {
32                     username.setAttribute(value"33                     password.setAttribute(34                     btn.click();
35                 }
36             }
37             catch (Exception ex) {
38 
39 40         }
41 
42         void compWait() {
43             while (!isLoad)
44 45                 Thread.Sleep(200);
46 47 48 
49         /// <summary>
50         /// 
51         </summary>
52         <param name="pdisp"></param>
53         <param name="URL"></param>
54         void Ie_DocumentComplete(object pdisp,1)">ref object URL)
55 56             isLoad = 57 58     }
59 }
View Code

备注

所谓的坚持,不过是每天努力一点点!!!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐