本文主要讲解通过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. 20191031-3 beta week 1/2 Scrum立会报告+燃尽图 01

    此作业要求参见[https://edu.cnblogs.com/campus/nenu/2019fall/homework/9911] 一.小组情况 队名:扛把子 组长:孙晓宇 组员:宋晓丽 梁梦瑶 ...

  2. [Odoo12基础教程]之第零篇-win中odoo12环境搭建

    所需材料 1.python3.7 2.pycharm社区版及以上 3.postgresSQL10 下载链接:https://www.enterprisedb.com/thank-you-downloa ...

  3. 使用Query Store监控性能

    Query Store是SQL Server 2016中引入的语句性能监控和调优工具,它不仅自动捕获查询.执行计划和运行时统计信息的历史记录,而且还可以识别出由于执行计划更改而导致的性能差异,简化了性 ...

  4. .NET Core 3.0之深入源码理解HealthCheck(一)

    写在前面 我们的系统可能因为正在部署.服务异常终止或者其他问题导致系统处于非健康状态,这个时候我们需要知道系统的健康状况,而健康检查可以帮助我们快速确定系统是否处于正常状态.一般情况下,我们会提供公开 ...

  5. Java基础面试题及答案(二)

    容器 18. java 容器都有哪些? 常用容器的图录: 19. Collection 和 Collections 有什么区别? java.util.Collection 是一个集合接口(集合类的一个 ...

  6. js人民币转大写

    <input type="text" oninput="OnInput (event)" value="1234567"> &l ...

  7. PHP常用字符串函数总结

    PHP语言中的字符串函数也是一个比较易懂的知识.今天我们就为大家总结了将近12种PHP字符串函数,希望对又需要的朋友有所帮助,增加读者朋友的PHP知识库. 1.查找字符位置函数 strpos($str ...

  8. mysql——中文数字排序的实现(FIELD)

    今天遇到一个需求,要求排序输出网格信息,但是数据是第三方对接插入的,并没有给我们排好顺序.所以只能自己动手了. 下图是原数据: 我们需要将其升序输出.使用mysql中的函数FIELD.语法如下: SE ...

  9. 大数据之Linux基础

    回顾这一个多月以来闭关学大数据的一些相关重要知识,就当复习,顺便以备以后查看 Linux学习第一步自然是安装Linux. 关于Linux 首先介绍下Linux,Linux系统很多程序员开发者其实都耳熟 ...

  10. Java 将Excel转为PDF

    本文将介绍在Java程序中如何将Excel工作簿转为PDF文档的,包括: 将整个工作簿转为PDF 将指定工作表转为PDF   使用工具:Free Spire.XLS for Java (免费版) Ja ...