//

分类: c# 2013-02-06 15:18 3008人阅读 评论(0) 收藏 举报

可以实现例如通过应用程序操作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

另外一个例子

IHTMLDocument2 doc = webbrowser.Document.DomDocument as IHTMLDocument2;
IHTMLBodyElement bodyElement = doc.body as IHTMLBodyElement;
if (bodyElement != null)
{

IHTMLTxtRange range = bodyElement.createTextRange();
        HTMLDocumentClass documentClass = wb1.Document.DomDocument as HTMLDocumentClass;
        IHTMLElement caret_pos = documentClass.getElementById("caret_pos");
        if (caret_pos != null)
       {
               range.moveToElementText(caret_pos);
               range.select();
        }
}

2011-3-14添加

给html元素添加事件

IHTMLElement ieElement = .......

((mshtml.HTMLElementEvents2_Event)ieElement).onclick += new mshtml.HTMLElementEvents2_onclickEventHandler(this.element_onClick);

public bool element_onClick(mshtml.IHTMLEventObj e)
{。。。。}

要在程序中出发html中的事件,这个想用什么eventhandler之类的,搞了半天都没有研究出来,资料又搜不到,最后用执行js的方法实现之:

js触发事件:

var oEvent = document.createEventObject();

document.getElementById('addrCity').fireEvent('onchange', oEvent);

c#控制IE浏览器自动点击等事件WebBrowser,mshtml.IHTMLDocument2 .的更多相关文章

  1. js去掉浏览器右键点击默认事件(+vue项目开启右键行为)

    js去掉浏览器右键点击默认事件 1.阻止整个页面所有的右击事件 document.oncontextmenu = function(){ return false;} 2.特定的区域/元素 docum ...

  2. javascript脚本实现浏览器自动点击(阿里员工秒杀月饼)

    原文地址https://blog.csdn.net/ani521smile/article/details/52575063 秒杀活动页面 <!DOCTYPE HTML> <html ...

  3. 在CMD下启动vmware、Xshell连接虚拟机以及控制Chrome浏览器自动执行js登录校园网

    标题有点长,主要是写个bat出来玩玩, (1)不用每次都手动关闭mysql服务(我不想把它设为手动启动,有强迫症) (2)然后希望每次vmware能自动连上虚拟机 (3)以及每次Xshell都能自动启 ...

  4. c# 控制IE浏览器

    原文 http://www.cnblogs.com/love2wllw/archive/2010/05/19/1739327.html 想写一个桌面程序,用C#.程序运行后,会用IE打开指定的网页,并 ...

  5. iphone 浏览器自动解析数字为号码解决方法

    iphone 浏览器自动解析数字为号码解决方法 www.MyException.Cn  网友分享于:2015-10-09  浏览:0次   iphone 浏览器自动解析数字为号码解决办法 在工作中遇到 ...

  6. SlimerJS – Web开发人员可编写 JS 控制的浏览器

    SlimerJS 是一个提供给 Web 开发人员,可通过脚本编程控制的浏览器.它可以让你使用 Javascript 脚本操纵一个网页:打开一个网页,点击链接,修改的内容等,这对于做功能测试,页面自动机 ...

  7. [原]用WebBrowser组件模拟人工运行搜索引擎自动点击搜索结果的实验

    本代码只是业余时间无聊写着试试,用WebBrowser组件模拟人工运行搜索引擎自动点击搜索结果的实验 这是网络中盛传的提高搜索引擎点击率的一种方式,当然属于作弊,不推荐各位使用.另外这种方式的性能不佳 ...

  8. Webpack 2 视频教程 007 - 配置 WDS 进行浏览器自动刷新

    原文发表于我的技术博客 这是我免费发布的高质量超清「Webpack 2 视频教程」. Webpack 作为目前前端开发必备的框架,Webpack 发布了 2.0 版本,此视频就是基于 2.0 的版本讲 ...

  9. 禁止Chrome浏览器自动升级

    对于我们测试人员来说,浏览器自动升级是非常可怕的,浏览器的升级会导致出现各种bug,比如我们常用的Selenium,如果Chrome浏览器自动升级就会导致脚本出错,无法打开浏览器等等情况,对于这种情况 ...

随机推荐

  1. css中table样式

    border-spacing:设置相邻单元格的边框间的距离; border-collapse:设置表格的边框是否被合并为一个单一的边框:{separate/collapse/inherit(IE不支持 ...

  2. canvas draw a image

    var c = context.getContext("2d"); var cimg = new Image(); cimg.src = "img path"; ...

  3. 图像滤波:Gabor滤波

  4. net.sf.json 时间格式的转化

    后台代码 //后台代码 response.setCharacterEncoding("UTF-8"); JsonConfig jsonConfig = new JsonConfig ...

  5. 'Invalid parameter not satisfying: body'

    afnetwork图片上传的时候出错,出现错误 2015-11-09 15:47:59.086 videoPro[3207:132795] *** Assertion failure in -[AFS ...

  6. ziparchiver添加后编译出错

    Build setting里面compile source as改为Objective-c

  7. 如何将arcgis的mxd文档存储为相对路径

    在默认情况下,ArcGIS 10中地图文件mxd中添加的图层所引用的文件路径均为绝对路径.这就意味着,如果你在地图中引用了“D:\data\DEM.shp”文件,那map.mxd文件中保存的该层文件路 ...

  8. Ubuntu解压命令大全

    tar 解包:tar xvf FileName.tar打包:tar cvf FileName.tar DirName(注:tar是打包,不是压缩!)———————————————.gz解压1:gunz ...

  9. Shell_参数替换(転)

    From: http://www.cnblogs.com/yjf512/archive/2013/06/03/3114803.html Bash中的$符号的作用是参数替换,将参数名替换为参数所代表的值 ...

  10. asp.net C# 未能加载文件或程序集或它的某一个依赖项。需要强名称程序集。的解决办法

    asp.net C# 未能加载文件或程序集或它的某一个依赖项.需要强名称程序集.的解决办法 出现这个错误是原因:是有签名的DLL引用了无签名的DLL 如上图所示,就是因为引用Entity.MVCEnt ...