C# 模拟浏览器并自动操作
本文主要讲解通过WebBrowser控件打开浏览页面,并操作页面元素实现自动搜索功能,仅供学习分享使用,如有不足之处,还请指正。
涉及知识点
- WebBrowser:用于在WinForm窗体中,模拟浏览器,打开并导航网页。
- HtmlDocument:表示一个Html文档的页面。每次加载都会是一个全新的页面。
- GetElementById(string id):通过ID或Name获取一个Html中的元素。
- HtmlElement:表示一个Html标签元素。
- 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# 模拟浏览器并自动操作的更多相关文章
- Python模拟浏览器前进后退操作
# 模拟浏览器前进后退操作 # 代码中引入selenium版本为:3.4.3 # 通过Chrom浏览器访问发起请求 # Chrom版本:59 ,chromdriver:2.3 # 需要对应版本的Chr ...
- splinter python浏览器自动化操作,模拟浏览器的行为
Splinter可以非常棒的模拟浏览器的行为,Splinter提供了丰富的API,可以获取页面的信息判断当前的行为所产生的结果 最近在研究网站自动登录的问题,涉及到需要实现浏览器自动化操作,网上有 ...
- 浏览器与服务器交互原理以及用java模拟浏览器操作v
浏览器应用服务器JavaPHPApache * 1,在HTTP的WEB应用中, 应用客户端和服务器之间的状态是通过Session来维持的, 而Session的本质就是Cookie, * 简单的讲,当浏 ...
- 孤荷凌寒自学python第八十五天配置selenium并进行模拟浏览器操作1
孤荷凌寒自学python第八十五天配置selenium并进行模拟浏览器操作1 (完整学习过程屏幕记录视频地址在文末) 要模拟进行浏览器操作,只用requests是不行的,因此今天了解到有专门的解决方案 ...
- python下selenium模拟浏览器基础操作
1.安装及下载 selenium安装: pip install selenium 即可自动安装selenium geckodriver下载:https://github.com/mozilla/ge ...
- casperjs配合phantomjs实现自动登录百度,模拟点击等等操作 - 怕虎在线www.ipahoo.com图文教程 - 怕虎在线
微信支付取消2万元保证金门槛,这是全民电商来袭!-观点-虎嗅网 微信支付取消2万元保证金门槛,这是全民电商来袭! casperjs配合phantomjs实现自动登录百度,模拟点击等等操作 - 怕虎在线 ...
- python3 scrapy 使用selenium 模拟浏览器操作
零. 在用scrapy爬取数据中,有写是通过js返回的数据,如果我们每个都要获取,那就会相当麻烦,而且查看源码也看不到数据的,所以能不能像浏览器一样去操作他呢? 所以有了-> Selenium ...
- php中curl模拟浏览器来传输数据
cURL可以使用URL的语法模拟浏览器来传输数据, 因为它是模拟浏览器,因此它同样支持多种协议,FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以 ...
- 【Python】 Selenium 模拟浏览器 寻路
selenium 最开始我碰到SE,是上学期期末,我们那个商务小组做田野调查时发的问卷的事情.当时在问卷星上发了个问卷,但是当时我对另外几个组员的做法颇有微词,又恰好开始学一些软件知识了,就想恶作剧( ...
随机推荐
- flexpaper跨服务器访问swf不显示问题
在项目中使用flexpaper.html在线预览时,发现文件存放在本地localhost能访问,在服务器上的无法访问,通常报错“loadswf() is not defined” 研究发现是跨域问题导 ...
- 2019-10-29:渗透测试,基础学习,sqlmap文件读取,写入,dnslog盲注作用,mssql手工注入,笔记
sqlmap参数--file-read,从数据库服务器中读取文件--file-write,--file-dest,把文件上传到数据库服务器中 dnslog平台的学习和它在盲注中的应用1,判断注入点2, ...
- numpy和matplotlib下载中出现的问题
在安装numpy的时候遇到如下所示的错误: 经过几个小时的查找,最终发现是pygame的路径不对导致.将pygame的具体路径加上后,问题解决.实施如下:得出一个结论:路径很重要,千万得小心哦. 报错 ...
- 01-tornado练习-tornado简介
# coding = utf-8 """ 启动一个tornado的web服务 """ import tornado.web from tor ...
- 2019 牛客网 第七场 H pair
题目链接:https://ac.nowcoder.com/acm/contest/887/H 题意: 给定A,B,C问在[1,A]和[1,B]中有多少对x,y满足x&y>C或者x^y ...
- 配置Tomcat监听80端口、配置Tomcat虚拟主机、Tomcat日志
6月27日任务 16.4 配置Tomcat监听80端口16.5/16.6/16.7 配置Tomcat虚拟主机16.8 Tomcat日志扩展邱李的tomcat文档 https://www.linuser ...
- UML类图绘制
UML图简介 含义:UML-Unified Modeling Language 统一建模语言,又称标准建模语言.是用来对软件密集系统进行可视化建模的一种语言 主要模型: 功能模型:从用户的角度展示系统 ...
- 鲲鹏凌云,并行科技Paramon通过华为云鲲鹏云服务兼容性认证
随着Cloud2.0时代到来,5G技术开始应用普及,超算云服务需求不断升级,业务多样性.数据多样性不断延伸.2019年7月,华为召开鲲鹏计算产业发展峰会,依托在联接领域坚实的基础,华为未来将着力打造智 ...
- 深入理解Android异步消息处理机制
一.概述 Android 中的异步消息处理主要分为四个部分组成,Message.Hndler.MessageQueue 和 Looper.其关系如下图所示: 1. Message 是线程之间传递的消息 ...
- [NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached
错误的意思是:已达到可容忍的服务器重连接错误的最大数目.有两个解决思路:一个将这个值设置的更大:然后是排查自己连接服务哪儿出了问题.先说在哪儿设置这个值:在拉取nacos服务的注解配置中,添加一个属性 ...