如何访问网页中的不同菜单和标签?

时间:2015-04-08 10:05:16

标签: excel-vba vba excel

我对VBA很新。

我必须在IE中打开某个网页。该网页左侧有一个菜单,每个菜单中都有不同的标签。

我必须检查所有这些菜单&选项卡已启动。除此之外,我必须检查这些页面上的错误(如果有的话显示)。

我已经能够编写代码来打开网页。

1 个答案:

答案 0 :(得分:0)

这是我几个月前写的一些代码。它检索网页的HTML Dom并尝试在该DOM中查找元素/ ID /类并返回其文本或html。

也许您可以使用它来查找菜单/标签,并检查其内容是否相符。此外,VBA的HTMLDocument / IHTMLElement类可能对您有用。

作为注释:它需要Microsoft Internet Controls和Microsoft HTML Object Library引用。

Public Function GetWebPage(url As String, Optional resultType As String = "innerText", Optional selector As Variant) As Variant
Dim oBrowser As InternetExplorer
Dim HTMLDoc As HTMLDocument
Dim docText As String
Dim arrSelector As Variant
Dim element As IHTMLElement
Dim i As Long
Dim tmpElementName As String
Dim timer As Long
Const waitTime = 12000

'// set the browser object to a new IE instance
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.Visible = False
oBrowser.Navigate url '// navigate to the given page

'// wait until the page is loaded, requires the sleep api of windows
timer = 0
Do
    timer = timer + 1
    Sleep 10
Loop Until oBrowser.ReadyState = READYSTATE_COMPLETE Or timer > waitTime

'// if the page is loaded
If oBrowser.ReadyState = READYSTATE_COMPLETE Then
    Set HTMLDoc = oBrowser.Document '// retrieve the document


    '// if a selector was given
    If Not IsMissing(selector) Then
        '// get the temporary element name, this assumes the selector contains a '#' or a '.'
        '// to represent an id or a class
        tmpElementName = Mid(selector, 2)

        '// check if it's an id, a class or a simple element and retrieve it
        If Left(selector, 1) = "#" Then
                Set element = HTMLDoc.getElementById(tmpElementName)
        ElseIf Left(selector, 1) = "." Then
                Set element = HTMLDoc.getElementsByClassName(tmpElementName)
        Else
                Set element = HTMLDoc.body
        End If
    Else
        Set element = HTMLDoc.body
    End If

    '// get either inner text or html, depending on selection
    If Not element Is Nothing Then
        If resultType = "innerText" Then
            docText = element.innerText
        ElseIf resultType = "innerHTML" Then
            docText = element.innerHTML
        End If
    End If

    '// clean up everything and return
    Set element = Nothing
    HTMLDoc.Close
    Set HTMLDoc = Nothing

    GetWebPage = IIf(docText = "", Null, docText)
Else
    GetWebPage = Null
End If

oBrowser.Quit
Set oBrowser = Nothing
End Function