C# 模拟浏览器并自动操作的实例代码

 更新时间:2020年07月10日 09:41:14   作者:Alan.hsiang  
这篇文章主要介绍了C# 模拟浏览器并自动操作的实例代码,文中讲解非常细致,帮助大家更好的理解和学习,感兴趣的朋友可以了解下

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

  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()触发事件。

示例核心代码

如下所示:

namespace AutoGas
{
 public class Program
 {
  private static bool isLoad = false;

  public static void Main(string[] args)
  {
   string logUrl = ConfigurationManager.AppSettings["logUrl"]; //登录Url
   string uid = ConfigurationManager.AppSettings["uid"];//用户名ID
   string pid = ConfigurationManager.AppSettings["pid"];//密码ID
   string btnid = ConfigurationManager.AppSettings["btnid"];//按钮ID
   string uvalue = ConfigurationManager.AppSettings["uvalue"];//用户名
   string pvalue = ConfigurationManager.AppSettings["pvalue"];//密码
   InternetExplorer ie = new InternetExplorerClass();
   ie.DocumentComplete += Ie_DocumentComplete;
   object c = null;
   ie.Visible = true;
   ie.Navigate(logUrl, ref c, ref c, ref c, ref c);
   ie.FullScreen = true;

   compWait();
   try
   {
    HTMLDocumentClass doc = (HTMLDocumentClass)ie.Document;
    IHTMLElement username = doc.getElementById(uid);
    IHTMLElement password = doc.getElementById(pid);
    IHTMLElement btn = doc.getElementById(btnid);
    //如果有session,则自动登录,不需要输入账号密码
    if (username != null && password != null && btn != null)
    {
     username.setAttribute("value", uvalue);
     password.setAttribute("value", pvalue);
     btn.click();
    }
   }
   catch (Exception ex) {

   }
  }

  public static void compWait() {
   while (!isLoad)
   {
    Thread.Sleep(200);
   }
  }

  /// <summary>
  ///
  /// </summary>
  /// <param name="pDisp"></param>
  /// <param name="URL"></param>
  private static void Ie_DocumentComplete(object pDisp, ref object URL)
  {
   isLoad = true;
  }
 }
}

以上就是C# 模拟浏览器并自动操作的实例代码的详细内容,更多关于C# 模拟浏览器并自动操作的资料请关注脚本之家其它相关文章!

相关文章

  • c# 线性回归和多项式拟合示例详解

    c# 线性回归和多项式拟合示例详解

    线性回归与多项式拟合是两种常用的回归分析方法,线性回归模型简单,易于计算,但只适用于线性关系的数据,多项式拟合能处理非线性数据,模型更复杂,拟合度更高,但容易产生过拟合问题,计算成本较高,适用场景不同,线性回归适合线性数据,多项式拟合适合非线性数据
    2024-10-10
  • Unity3D使用UGUI开发原生虚拟摇杆

    Unity3D使用UGUI开发原生虚拟摇杆

    这篇文章主要为大家详细介绍了Unity3D使用UGUI开发原生虚拟摇杆,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-04-04
  • C#使用表达式树(LambdaExpression)动态更新类的属性值(示例代码)

    C#使用表达式树(LambdaExpression)动态更新类的属性值(示例代码)

    这篇文章主要介绍了C#使用表达式树(LambdaExpression)动态更新类的属性值,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-01-01
  • 详解Asp.Net MVC的Bundle捆绑

    详解Asp.Net MVC的Bundle捆绑

    这篇文章主要介绍了Asp.Net MVC的Bundle捆绑方法,具体实现方法给大家做代码整理,一起参考一下。
    2017-11-11
  • 深入理解C# DateTime日期格式化

    深入理解C# DateTime日期格式化

    在C#中DateTime是一个包含日期、时间的类型,此类型通过ToString()转换为字符串时,可根据传入给Tostring()的参数转换为多种字符串格式。
    2017-01-01
  • C#实现骑士飞行棋

    C#实现骑士飞行棋

    这篇文章主要为大家详细介绍了C#实现骑士飞行棋,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-02-02
  • C#实现日期时间的格式化输出的示例详解

    C#实现日期时间的格式化输出的示例详解

    这篇文章主要为大家详细介绍了C#实现日期时间的格式化输出的相关资料,文中的示例代码讲解详细,具有一定的借鉴价值,需要的可以参考一下
    2023-03-03
  • C#实现FFT(递归法)的示例代码

    C#实现FFT(递归法)的示例代码

    FFT是数字信号处理中的重要算法。这篇文章将为大家详细介绍一下如何利用C#语言实现FFT(递归法),文中的示例代码讲解详细,感兴趣的可以了解一下
    2022-07-07
  • C#抽象类与抽象方法详解

    C#抽象类与抽象方法详解

    这篇文章主要为大家详细介绍了C#抽象类与抽象方法的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-10-10
  • C#利用Refit实现JWT自动续期详解

    C#利用Refit实现JWT自动续期详解

    Refit 是一个受到Square的Retrofit库(Java)启发的自动类型安全REST库,这篇文章主要为大家介绍了C#如何利用Refit实现JWT自动续期,感兴趣的可以了解下
    2023-08-08

最新评论