C#操作IE
操作IE主要使用两个Com Dll:
1、Microsoft Internet Controls
2、Microsoft HTML Object Library
使用Microsoft Internet Controls取得所有的已经打开的IE(以Tab计算)
SHDocVw.ShellWindows IETabs = new SHDocVw.ShellWindows();
每个一个Tab都可以操作,每个Tab对应Com Object的SHDocVw.InternetExplorer
foreach (SHDocVw.InternetExplorer ieTab in IETabs)
{
}
取得每个Tab之后,就可以通过InternetExplorer的Document取得每个页面的Dom
mshtml.HTMLDocument dom = ieTab.Document as mshtml.HTMLDocument;
取得Dom之后,基本上就已经取得了操作IE的所有权限了,可以继续使用HTML Object Library对页面进行操作
或者通过注册JavaScript,对页面进行操作:
mshtml.IHTMLScriptElement script = dom.createElement("script") as mshtml.IHTMLScriptElement; \\创建script标签
script.text = "$(\"[name='wd']\").val('刘德华');"; \\通过Jquery,对百度进行操作
mshtml.HTMLBody body = dom.body as mshtml.HTMLBody; \\取得body对象
body.appendChild((mshtml.IHTMLDOMNode)script); \\注册JavaScript
完整代码(循环所有ieTab,对百度页面操作...搜索刘德华):
SHDocVw.ShellWindows IETabs = new SHDocVw.ShellWindows(); foreach (SHDocVw.InternetExplorer ieTab in IETabs) { if (ieTab.LocationURL.Contains("www.baidu.com")) { mshtml.HTMLDocument doc = ieTab.Document as mshtml.HTMLDocument; mshtml.IHTMLScriptElement script = doc.createElement("script") as mshtml.IHTMLScriptElement; script.text = "$(\"[name='wd']\").val('刘德华');"; mshtml.HTMLBody body = doc.body as mshtml.HTMLBody; body.appendChild((mshtml.IHTMLDOMNode)script); } }
园里有其他更加详细的参考Blog:
c#控制IE浏览器自动点击等事件WebBrowser,mshtml.IHTMLDocument2
个人建议:
基本接入IE,使用Com,然后其他业务操作,通过注入JavaScript进行操作