本文主要讲解通过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. 堆 堆排序 优先队列 图文详解(Golang实现)

    引入 在实际应用中,我们经常需要从一组对象中查找最大值或最小值.当然我们可以每次都先排序,然后再进行查找,但是这种做法效率很低.哪么有没有一种特殊的数据结构,可以高效率的实现我们的需求呢,答案就是堆( ...

  2. CSS中如何使用背景样式属性,看这篇文章就够用了

    css背景样式属性介绍 背景样式就是自定义HTML标签的背景颜色或背景图像. 背景属性说明表 属性名 属性值 描述 background-color #f00.red.rgb(255,0,0) 设置背 ...

  3. es6 every的使用

    let arr2 =[1,3,5,7,9,10]; //arr2.every() 数组里面所有的元素都有符合条件,才返回true var b =arr2.every(function (val,ind ...

  4. Java架构师必知:什么是单点登录,主要会应用于哪些场景?

    单点登录在大型网站里使用得非常频繁,例如,阿里旗下有淘宝.天猫.支付宝,阿里巴巴,阿里妈妈,阿里妹妹等网站,还有背后的成百上千的子系统,用户一次操作或交易可能涉及到几十个子系统的协作,如果每个子系统都 ...

  5. C#学习笔记03--循环和一维数组

    一.循环(重点) 什么时候用循环? 想让一段代码执行多次, 这段代码可能不一样但是一定有一个规律. 1.while 循环 格式:  while(循环条件) { 循环执行的代码; } 循环的机制:  当 ...

  6. 盒模型 | CSS权重 | CSS层叠

    span{ color:red;} *{ font-family:"楷体";line-height:2em; font-size:18px;} 盒模型 CSS定义所有的元素都可能拥 ...

  7. 69道Spring面试题及答案

    目录 Spring 概述 依赖注入 Spring beans Spring注解 Spring数据访问 Spring面向切面编程(AOP) Spring MVC Spring 概述 1. 什么是spri ...

  8. Java 浅拷贝、深拷贝,你知多少?

    这是今天我们在技术群里面讨论的一个知识点,讨论的相当激烈,由于对这一块使用的比较少,所以对这一块多少有些盲区.这篇文章总结了所讨论的内容,希望这篇文章对你有所帮助. 在 Java 开发中,对象拷贝或者 ...

  9. python初识-环境搭建,变量,条件,循环语句

    1.python环境搭建: (1)安装Anaconda ,可选择非C盘安装: 注意:都勾选: (2)安装Pycharm 默认安装即可,安装过程同样都勾选: (3)破解Pycharm https://w ...

  10. Vue项目功能插件

    项目功能插件 vue-router { path: '/', name: 'home', // 路由的重定向 redirect: '/home' } { // 一级路由, 在根组件中被渲染, 替换根组 ...