C# 模拟浏览器并自动操作
2021-01-23 13:11
标签:png eric dev https handler pac 获取 rgs pwa 本文主要讲解通过WebBrowser控件打开浏览页面,并操作页面元素实现自动搜索功能,仅供学习分享使用,如有不足之处,还请指正。 主要采用异步等待的方式,等待页面加载完成,流程如下所示: 如下所示:加载完成后,自动输入【天安门】并点击搜索。 加载新的页面,如下所示: 注意:this.wb01.ScriptErrorsSuppressed = true;用于是否弹出异常脚本代码错误框 获取元素并赋值,如下所示: 示例整体代码,如下所示: 所谓的坚持,不过是每天努力一点点!!! C# 模拟浏览器并自动操作 标签:png eric dev https handler pac 获取 rgs pwa 原文地址:https://www.cnblogs.com/hsiang/p/12070950.html涉及知识点
设计思路
示例效果图
核心代码
1 string url = "https://www.so.com/";
2 this.wb01.ScriptErrorsSuppressed = true;
3 this.wb01.Navigate(url);
1 string search_id = "input";
2 string search_value = "天安门";
3 string btn_id = "search-button";
4 HtmlDocument doc = this.wb01.Document;
5 HtmlElement search = doc.GetElementById(search_id);
6 search.SetAttribute("value", search_value);
7 HtmlElement btn = doc.GetElementById(btn_id);
8 btn.InvokeMember("click");
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading;
9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11
12 namespace DemoExplorer
13 {
14 public partial class FrmExplorer : Form
15 {
16 private bool isLoadOk = false;
17
18 private BackgroundWorker bgWork;
19
20 public FrmExplorer()
21 {
22 InitializeComponent();
23 }
24
25 private void FrmExplorer_Load(object sender, EventArgs e)
26 {
27 bgWork = new BackgroundWorker();
28 bgWork.DoWork += bgWork_DoWork;
29 bgWork.RunWorkerCompleted += bgWork_RunWorkerCompleted;
30 string url = "https://www.so.com/";
31 this.wb01.ScriptErrorsSuppressed = true;
32 this.wb01.Navigate(url);
33 bgWork.RunWorkerAsync();
34 }
35
36 private void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
37 {
38 string search_id = "input";
39 string search_value = "天安门";
40 string btn_id = "search-button";
41 HtmlDocument doc = this.wb01.Document;
42 HtmlElement search = doc.GetElementById(search_id);
43 search.SetAttribute("value", search_value);
44 HtmlElement btn = doc.GetElementById(btn_id);
45 btn.InvokeMember("click");
46 }
47
48 private void bgWork_DoWork(object sender, DoWorkEventArgs e)
49 {
50 compWait();
51 }
52
53 private void compWait()
54 {
55 while (!isLoadOk)
56 {
57 Thread.Sleep(500);
58 }
59 }
60
61 private void wb01_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
62 {
63 this.wb01.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);
64 if (this.wb01.ReadyState == WebBrowserReadyState.Complete)
65 {
66 isLoadOk = true;
67 }
68 else
69 {
70 isLoadOk = false;
71 }
72 }
73
74 private void Window_Error(object sender, HtmlElementErrorEventArgs e)
75 {
76 e.Handled = true;
77 }
78 }
79 }
备注
上一篇:CSS水平垂直居中方式
下一篇:C# WPF实用的注册窗体