本文主要讲解通过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 }

备注

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

C# 模拟浏览器并自动操作的更多相关文章

  1. Python模拟浏览器前进后退操作

    # 模拟浏览器前进后退操作 # 代码中引入selenium版本为:3.4.3 # 通过Chrom浏览器访问发起请求 # Chrom版本:59 ,chromdriver:2.3 # 需要对应版本的Chr ...

  2. splinter python浏览器自动化操作,模拟浏览器的行为

    Splinter可以非常棒的模拟浏览器的行为,Splinter提供了丰富的API,可以获取页面的信息判断当前的行为所产生的结果   最近在研究网站自动登录的问题,涉及到需要实现浏览器自动化操作,网上有 ...

  3. 浏览器与服务器交互原理以及用java模拟浏览器操作v

    浏览器应用服务器JavaPHPApache * 1,在HTTP的WEB应用中, 应用客户端和服务器之间的状态是通过Session来维持的, 而Session的本质就是Cookie, * 简单的讲,当浏 ...

  4. 孤荷凌寒自学python第八十五天配置selenium并进行模拟浏览器操作1

    孤荷凌寒自学python第八十五天配置selenium并进行模拟浏览器操作1 (完整学习过程屏幕记录视频地址在文末) 要模拟进行浏览器操作,只用requests是不行的,因此今天了解到有专门的解决方案 ...

  5. python下selenium模拟浏览器基础操作

    1.安装及下载 selenium安装: pip install selenium  即可自动安装selenium geckodriver下载:https://github.com/mozilla/ge ...

  6. casperjs配合phantomjs实现自动登录百度,模拟点击等等操作 - 怕虎在线www.ipahoo.com图文教程 - 怕虎在线

    微信支付取消2万元保证金门槛,这是全民电商来袭!-观点-虎嗅网 微信支付取消2万元保证金门槛,这是全民电商来袭! casperjs配合phantomjs实现自动登录百度,模拟点击等等操作 - 怕虎在线 ...

  7. python3 scrapy 使用selenium 模拟浏览器操作

    零. 在用scrapy爬取数据中,有写是通过js返回的数据,如果我们每个都要获取,那就会相当麻烦,而且查看源码也看不到数据的,所以能不能像浏览器一样去操作他呢? 所以有了-> Selenium ...

  8. php中curl模拟浏览器来传输数据

    cURL可以使用URL的语法模拟浏览器来传输数据, 因为它是模拟浏览器,因此它同样支持多种协议,FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以 ...

  9. 【Python】 Selenium 模拟浏览器 寻路

    selenium 最开始我碰到SE,是上学期期末,我们那个商务小组做田野调查时发的问卷的事情.当时在问卷星上发了个问卷,但是当时我对另外几个组员的做法颇有微词,又恰好开始学一些软件知识了,就想恶作剧( ...

随机推荐

  1. 2019-9-28:渗透测试,phpstudy后门,利用复现

    9月20号爆出Phpstudy存在隐藏后门,简单复现下后门效果 该文章仅供学习,利用方法来自网络文章,仅供参考 目标机:win7系统,安装phpstudy 2018版,php版本5.2或php 5.4 ...

  2. 【翻译】Orleans 3.0 发布

    aaarticlea/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUF ...

  3. 使用laravel快速构建vuepress管理器

    使用laravel快速构建vuepress管理器 介绍 刚刚学了下laravel感觉很方便,最近也在用vuepress做个人博客,但是感觉每次写文章管理文章不是特别方便,就使用laravel写了这个v ...

  4. SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".错误的解决方法

    1.今天新git下来的项目报错如下: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: ...

  5. php 精度计算问题

    PHP var_dump(intval(0.58 * 100)); 正确结果是 57,而不是 58 浮点运算惹的祸 其实这些结果都并非语言的 bug,但和语言的实现原理有关, js 所有数字统一为 N ...

  6. PAT甲级专题|链表

    PAT链表专题 关于PAT甲级的链表问题,主要内容 就是"建立链表" 所以第一步学会模拟链表,pat又不卡时间,这里用vector + 结构体,更简洁 模拟链表的普遍代码 cons ...

  7. 2019-2020-11 20199304 《Linux内核原理与分析》 第十一周作业

    缓冲区溢出漏洞实验 一.简介 缓冲区溢出是指程序试图向缓冲区写入超出预分配固定长度数据的情况.这一漏洞可以被恶意用户利用来改变程序的流控制,甚至执行代码的任意片段.这一漏洞的出现是由于数据缓冲器和返回 ...

  8. ThinkPHP5——模型关联(多对多关联)

    关联定义 多对多关联不像一对一和一对多关联,它还要多建一个中间表用来处理多对多的关联,例如: #城市 create table city ( c_id int primary key AUTO_INC ...

  9. 【Python成长之路】词云图制作

    [写在前面] 以前看到过一些大神制作的词云图 ,觉得效果很有意思.如果有朋友不了解词云图的效果,可以看下面的几张图(图片都是网上找到的): 网上找了找相关的软件,有些软件制作 还要付费.结果前几天在大 ...

  10. vue 常用的官网

    vue.js     https://cn.vuejs.org/ v-charts  https://v-charts.js.org/#/                    (图表,地图) web ...