使用 shdocvw.dll 和 mshtml.tlb 自动化 Internet Explorer – 一个案例研究
使用 shdocvw.dll 和 mshtml.dll 自动化 Internet Explorer。
引言
Microsoft Internet Explorer 附带了一个相当全面的,但文档稀疏的对象模型。 如果您使用过 Access 中的 Web 浏览器控件,那么您已经熟悉 IE 的对象模型的功能。 IE 对象模型中的所有功能(不包括外部支持,如脚本支持等)都由以下两个 DLL 提供
- shdocvw.dll (Microsoft Internet Controls)
- mshtml.tlb (Microsoft HTML 对象库)
您可以自动化 IE 以在本地保存 HTML 文件,检查所有元素,并在运行时解析特定的项目。
这里有一些示例代码,它通过 Internet Explorer Windows 登录到 rediffmail.com,如果用户名和密码有效。
首先,应用程序打开 http://rediff.com 网站。 它在指定位置输入用户名和密码,然后单击“提交”按钮,从而进入收件箱页面。 它还为特定用户打开撰写页面。
该应用程序大量使用 shdocvw.InternetExplorer
对象和 mshtml.Document
对象。
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim wbBrowser As New SHDocVw.InternetExplorer wbBrowser.Visible = True
wbBrowser.Navigate("http://www.rediff.com", Nothing, Nothing, Nothing, Nothing)
Do
Loop Until Not wbBrowser.Busy
LoginIntoSite(wbBrowser)
OpennComposePage(wbBrowser)
End Sub
Public Sub LoginIntoSite(ByRef wbBrowser As SHDocVw.InternetExplorer)
Dim HTMLDoc As mshtml.HTMLDocument
Do
Loop Until Not wbBrowser.Busy
HTMLDoc = wbBrowser.Document
Dim iHTMLCol As IHTMLElementCollection
Dim iHTMLEle As IHTMLElement
Dim str, userName, passwd As String
iHTMLCol = HTMLDoc.getElementsByTagName("input")
' Type the user name in the username text box
For Each iHTMLEle In iHTMLCol
If Not iHTMLEle.getAttribute("name") Is Nothing Then
str = iHTMLEle.getAttribute("name").ToString
If str = "login" Then
iHTMLEle.setAttribute("value", "<VALID USER NAME>")
Exit For
End If
End If
Next
' Type the password in the password text box
For Each iHTMLEle In iHTMLCol
If Not iHTMLEle.getAttribute("name") Is Nothing Then
str = iHTMLEle.getAttribute("name").ToString
If str = "passwd" Then
iHTMLEle.setAttribute("value", "<VALID PASSWORD>")
Exit For
End If
End If
Next
' Press the submit button
For Each iHTMLEle In iHTMLCol
If Not iHTMLEle.getAttribute("name") Is Nothing Then
If iHTMLEle.outerHTML = "<INPUT type=image" & _
" height=21 width=26 " & _
"src=""http://im.rediff.com/" & _
"uim/rm_go_but.gif"" border=0>" Then
iHTMLEle.click()
Exit For
End If
End If
Next
Do
Loop Until Not wbBrowser.Busy
End Sub
Public Sub OpenComposePage(ByRef wbBrowser As SHDocVw.InternetExplorer)
Dim HTMLDoc1 As mshtml.HTMLDocument
Dim iHtmlCol As IHTMLElementCollection
Dim iHtmlEle As IHTMLElement
Do
Loop Until Not wbBrowser.Busy
HTMLDoc1 = mshtml.HTMLDocument
iHtmlCol = HTMLDoc1.getElementsByTagName("a")
' Press the anchor tag to open compose page
For Each iHtmlEle In iHtmlCol
If Not iHtmlEle.outerText Is Nothing Then
If iHtmlEle.outerText.ToLower = "write mail".ToLower Then
iHtmlEle.click()
Exit For
End If
End If
Next
Do
Loop Until Not wbBrowser.Busy
End Sub