c#控制IE浏览器自动点击等事件WebBrowser,mshtml.IHTMLDocument2

本文主要是介绍c#控制IE浏览器自动点击等事件WebBrowser,mshtml.IHTMLDocument2,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

可以实现例如通过应用程序操作google搜索,用户输入要搜索的内容,然后在google中搜索;可以自动点击网页上的按钮等功能

    1. 加入对Microsoft Internet Controls的引用;
    2. 加入对Microsoft HTML Object Library的引用;

(要引入Microsoft.mshtml.dll 地址是C:/Program Files/Microsoft.NET/Primary Interop Assemblies)
    3. 通过mshtml.IHTMLDocument2、SHDocVw.InternetExplorer、SHDocVw.ShellWindowsClass获取当前打开的google搜索页面的IE窗口句柄;
    4. 根据3返回的句柄,获得当前打开的google页面的mshtml.IHTMLDocument2对象;
    5. 根据4返回的IHTMLDocument2对象,获得搜索输入框和提交按钮(可查看google页面源文件,确认输入框和提交按钮的类型和名字);
    6. 在搜索输入框中输入要搜索的内容,并执行提交按钮的click动作即可进行搜索;

 

简单来说:

打开ie:

SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
object objFlags = 1;
object objTargetFrameName = "";
object objPostData = "";
object objHeaders = "";
SHDocVw.InternetExplorer webBrowser1= (SHDocVw.InternetExplorer)shellWindows.Item(shellWindows.Count-1);
webBrowser1.Navigate(“http://www.google.cn”, ref objFlags, ref objTargetFrameName, ref objPostData, ref objHeaders);

(可以简略点写:object c=null; myWeb.Navigate("http://zhidao.baidu.com/",ref c,ref c,ref c,ref c); )
mshtml.IHTMLDocument2 htmlDoc = webBrowser1.Document as mshtml.IHTMLDocument2;

 

//...获取WebBroswer中的body代码
mshtml.HTMLDocumentClass doc=(mshtml.HTMLDocumentClass)myWeb.Document;
mshtml.HTMLBody body=(mshtml.HTMLBody)docCC.body;
string html=body.innerHTML.ToString();

//...如果里面有Form,要给里面的text填充信息
mshtml.IHTMLDocument2 doc2=(mshtml.IHTMLDocument2)myWeb.Document;
mshtml.IHTMLElementCollection inputs;
inputs=(mshtml.IHTMLElementCollection)doc2.all.tags("INPUT");
mshtml.IHTMLElement element=(mshtml.IHTMLElement)inputs.item("userName",0);
mshtml.IHTMLInputElement inputElement=(mshtml.IHTMLInputElement)element;
inputElement.value="填充信息";

//...要点击里面的某个按钮
mshtml.IHTMLDocument2 doc2=(mshtml.IHTMLDocument2)myWeb.Document;
mshtml.IHTMLElementCollection inputs;
inputs=(mshtml.IHTMLElementCollection)doc2.all.tags("INPUT");
mshtml.IHTMLElement element=(mshtml.IHTMLElement)inputs.item("SubmitBut",0);
element.click();

 

1、根据元素ID获取元素的值。

比如要获取<img class="" id="regimg" src="/register/checkregcode.html?1287068791" width="80" height="22">这个标签里的src属性的值:

mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)webBrowser1.Document;
mshtml.IHTMLElement img = (mshtml.IHTMLElement)doc2.all.item("regimg", 0);

string imgUrl = (string)img.getAttribute("src");

2、填写表单,并确定

mshtml.IHTMLElement loginname = (mshtml.IHTMLElement)doc2.all.item("loginname", 0);
    mshtml.IHTMLElement loginPW = (mshtml.IHTMLElement)doc2.all.item("password", 0);
    mshtml.IHTMLElement loginBT = (mshtml.IHTMLElement)doc2.all.item("formsubmit", 0);
    mshtml.IHTMLElement loginYZ = (mshtml.IHTMLElement)doc2.all.item("regcode", 0);
    loginname.setAttribute("value", tbLoginName.Text);
    loginPW.setAttribute("value", tbLoginPassWord.Password);
    loginYZ.setAttribute("value", tbYZ.Text);
    loginBT.click();

3、获取源码

textBox1.Text = doc2.body.innerHTML;

4、执行JS

mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)doc2.parentWindow;
win.execScript("changeRegImg()", "javascript");//使用JS

5、禁止JS,WPF下目前发现唯一适用的一种方法:

public void HideScriptErrors(WebBrowser wb, bool Hide)
   {

    FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);

    if (fiComWebBrowser == null) return;

    object objComWebBrowser = fiComWebBrowser.GetValue(wb);

    if (objComWebBrowser == null) return;

    objComWebBrowser.GetType().InvokeMember(

    "Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });

   }

   void webBrowser1_Navigated(object sender, NavigationEventArgs e)
   {

    HideScriptErrors(webBrowser1,

    true);

   }

 

 

 

下面是另外一遍博客里写的比较好的

#region Search    
        public static void Search(string searchText)   
        {   
            SHDocVw.InternetExplorer ieWnd = GetIEWndOfGoogle();   
            mshtml.IHTMLDocument2 ieDoc = GetIEDocOfGoogle(ref ieWnd);   
  
            System.Diagnostics.Trace.Assert(ieDoc != null);   
            SearchTextInGoogle(ieDoc, searchText);   
  
            //activate ie window    
            SetForegroundWindow(ieWnd.HWND);               
        }   
        #endregion   
 
        #region get ie window of google page    
        public static SHDocVw.InternetExplorer GetIEWndOfGoogle()   
        {   
            mshtml.IHTMLDocument2 ieDoc;   
            SHDocVw.InternetExplorer ieWnd = null;   
            SHDocVw.ShellWindowsClass shellWindows = new SHDocVw.ShellWindowsClass();   
  
            foreach (SHDocVw.InternetExplorer ie in shellWindows)   
            {   
                //if it is ie window    
                if (ie.FullName.ToUpper().IndexOf("IEXPLORE.EXE") > 0)   
                {   
                    //get the document displayed    
                    ieDoc = (mshtml.IHTMLDocument2)ie.Document;   
                    if (ieDoc.title.ToUpper().IndexOf("GOOGLE") >= 0)   
                    {   
                        ieWnd = ie;   
                        break;   
                    }   
                }   
            }   
               
            shellWindows = null;   
  
            return ieWnd;   
        }   
        #endregion   
 
        #region get ie document of google page    
        public static mshtml.IHTMLDocument2 GetIEDocOfGoogle(ref SHDocVw.InternetExplorer ieWnd)   
        {   
            object missing = null;   
            mshtml.IHTMLDocument2 ieDoc;   
  
            if (ieWnd == null)   
            {   
                ieWnd = new SHDocVw.InternetExplorer();   
                ieWnd.Visible = true;   
                ieWnd.Navigate("http://www.google.com", ref missing, ref missing, ref missing, ref missing);   
  
                //wait for loading completed, or using DocumentComplete Event    
                while (ieWnd.StatusText.IndexOf("完成") == -1)   
                    Application.DoEvents();   
            }   
  
            ieDoc = (mshtml.IHTMLDocument2)ieWnd.Document;   
            return ieDoc;   
        }   
        #endregion

#region Search the given text in google    
        / <summary>    
        /// search the given text in google home page    
        /// we can see the source file of google home page to confirm the elements we need    
        /// the html file of google home page is as follows    
        ///     
        /// <table cellpadding=0 cellspacing=0>    
        ///     <tr valign=top>    
        ///         <td width=25%> </td>    
        ///         <td align=center nowrap>    
        ///             <input name=hl type=hidden value=zh-CN>    
        ///             <input autocomplete="off" maxlength=2048 name=q size=55 title="Google 搜索" value="">    
        ///             <br>    
        ///             <input name=btnG type=submit value="Google 搜索">    
        ///             <input name=btnI type=submit value=" 手气不错 ">    
        ///         </td>    
        ///         ...    
        / </summary>            
        public static void SearchTextInGoogle(mshtml.IHTMLDocument2 ieDoc, string searchText)   
        {   
            mshtml.HTMLInputElementClass input;   
  
            //set the text to be searched    
            foreach (mshtml.IHTMLElement ieElement in ieDoc.all)   
            {   
                //if its tag is input and name is q(question)    
                if (ieElement.tagName.ToUpper().Equals("INPUT"))   
                {   
                    input = ((mshtml.HTMLInputElementClass)ieElement);   
                    if (input.name == "q")   
                    {   
                        input.value = searchText;   
                        break;   
                    }   
                }   
            }   
  
            //click the submit button to search    
            foreach (mshtml.IHTMLElement ieElement in ieDoc.all)   
            {   
                //if its tag is input    
                if (ieElement.tagName.ToUpper().Equals("INPUT"))   
                {   
                    input = (mshtml.HTMLInputElementClass)ieElement;   
                    if (input.name == "btnG")   
                    {   
                        input.click();   
                        break;   
                    }   
                }   
            }   
        }   
        #endregion  

 

参考文章:

http://blog.csdn.net/livelylittlefish/archive/2008/08/25/2829873.aspx

http://hi.baidu.com/andyleesoft/blog/item/802e02289fcc1f94023bf66a.html

http://zhidao.baidu.com/question/48084010.html

这篇关于c#控制IE浏览器自动点击等事件WebBrowser,mshtml.IHTMLDocument2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/682244

相关文章

Python将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

微信公众号脚本-获取热搜自动新建草稿并发布文章

《微信公众号脚本-获取热搜自动新建草稿并发布文章》本来想写一个自动化发布微信公众号的小绿书的脚本,但是微信公众号官网没有小绿书的接口,那就写一个获取热搜微信普通文章的脚本吧,:本文主要介绍微信公众... 目录介绍思路前期准备环境要求获取接口token获取热搜获取热搜数据下载热搜图片给图片加上标题文字上传图片

在React中引入Tailwind CSS的完整指南

《在React中引入TailwindCSS的完整指南》在现代前端开发中,使用UI库可以显著提高开发效率,TailwindCSS是一个功能类优先的CSS框架,本文将详细介绍如何在Reac... 目录前言一、Tailwind css 简介二、创建 React 项目使用 Create React App 创建项目

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

详解C#如何提取PDF文档中的图片

《详解C#如何提取PDF文档中的图片》提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使用,下面我们就来看看如何使用C#通过代码从PDF文档中提取图片吧... 当 PDF 文件中包含有价值的图片,如艺术画作、设计素材、报告图表等,提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

用js控制视频播放进度基本示例代码

《用js控制视频播放进度基本示例代码》写前端的时候,很多的时候是需要支持要网页视频播放的功能,下面这篇文章主要给大家介绍了关于用js控制视频播放进度的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言html部分:JavaScript部分:注意:总结前言在javascript中控制视频播放

C#数据结构之字符串(string)详解

《C#数据结构之字符串(string)详解》:本文主要介绍C#数据结构之字符串(string),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录转义字符序列字符串的创建字符串的声明null字符串与空字符串重复单字符字符串的构造字符串的属性和常用方法属性常用方法总结摘

C#如何动态创建Label,及动态label事件

《C#如何动态创建Label,及动态label事件》:本文主要介绍C#如何动态创建Label,及动态label事件,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#如何动态创建Label,及动态label事件第一点:switch中的生成我们的label事件接着,