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

涉及知识点

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

设计思路

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

示例效果图

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

核心代码

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

 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();
}
} 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()触发事件。

示例核心代码

如下所示:

 1 namespace AutoGas
2 {
3 public class Program
4 {
5 private static bool isLoad = false;
6
7 public static 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 = null;
18 ie.Visible = true;
19 ie.Navigate(logUrl, ref c, ref c, ref c, ref c);
20 ie.FullScreen = true;
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 != null)
31 {
32 username.setAttribute("value", uvalue);
33 password.setAttribute("value", pvalue);
34 btn.click();
35 }
36 }
37 catch (Exception ex) {
38
39 }
40 }
41
42 public static 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 private static void Ie_DocumentComplete(object pDisp, ref object URL)
55 {
56 isLoad = true;
57 }
58 }
59 }

备注

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

最新文章

  1. 安卓初級教程(4):sqlite建立資料庫
  2. About_Web
  3. springMVC中文乱码问题
  4. DFS --- HNU 13307 Galaxy collision
  5. 结构体. -&gt;操作符的内涵
  6. event.srcElement在火狐(FireFox)下的兼容问题。搜索框获得焦点时默认文字变化
  7. js 正则表达式 手机号
  8. 非常难得的iPad版房地产售楼助手应用
  9. 初涉Node.js
  10. CORREL
  11. C文件函数总结
  12. SICP 练习 (2.9)解决摘要:宽度和区间运算的关系间隔
  13. 【LeetCode】258. Add Digits
  14. C语言编译过程及数据类型
  15. JavaScript是如何工作的:编写自己的Web开发框架 + React及其虚拟DOM原理
  16. jpython basic
  17. Eclipse导入hadoop源码
  18. &lt;数字签名是什么&gt;笔记
  19. centos7上安装nodejs
  20. ASP.net中aspx与cs函数的互调

热门文章

  1. 【Linux系列】Centos 7安装 Redis(六)
  2. 记录用户登陆信息,你用PHP是如何来实现的
  3. Github远程库与Git本地库连接
  4. Glibc编译报错:*** LD_LIBRARY_PATH shouldn&#39;t contain the current directory when*** building glibc. Please change the environment variable
  5. 窗体的FormBorderStyle属性的不同效果
  6. Rust 入门 (四)
  7. 程序员的算法课(20)-常用的图算法:最小生成树(MST)
  8. java中关键字volatile的作用(转载)
  9. Docker harbor 安装和基础操作
  10. 关于使用Java Mail发邮件的问题