如何获取元名称关键字-vba

时间:2015-12-18 14:21:24

标签: vba excel-vba parsing html-parsing getelementsbytagname

我正在尝试从webpage

获取元名称关键字
  

meta name =“keywords”content =“Mitch Albom,For One More Day,Little,Brown Book Group,0751537535,Fiction / General,General& Literary Fiction,Modern& current fiction(post c 1945),USA

我需要从中获取内容需要帮助。

Option Explicit

Sub GetData()
    Dim ie As New InternetExplorer
    Dim str As String
    Dim wk As Worksheet
    Dim webpage As New HTMLDocument
    Dim item As HTMLHtmlElement

    Set wk = Sheet1
    str = wk.Range("Link").value
    ie.Visible = True

    ie.Navigate str

    Do
        DoEvents
    Loop Until ie.ReadyState = READYSTATE_COMPLETE

    Dim Doc As HTMLDocument
    Set Doc = ie.Document

    Dim kwd As String
    kwd = Trim(Doc.getElementsByTagName("keywords").innerText)
    MsgBox kwd

End Sub

1 个答案:

答案 0 :(得分:1)

最好的方法是找到名为 keyword 的元素并引用其content属性。你可以这样做:

Option Explicit

Sub GetData()
    Dim ie As New InternetExplorer
    Dim str As String
    Dim wk As Worksheet
    Dim webpage As New HTMLDocument
    Dim item As HTMLHtmlElement

    Set wk = Sheet1
    str = wk.Range("Link").value
    ie.Visible = True

    ie.Navigate str

    Do
        DoEvents
    Loop Until ie.ReadyState = READYSTATE_COMPLETE


    'Find the proper meta element --------------
    Const META_TAG As String = "META"
    Const META_NAME As String = "keywords"
    Dim Doc As HTMLDocument
    Dim metaElements As Object
    Dim element As Object
    Dim kwd As String


    Set Doc = ie.Document
    Set metaElements = Doc.all.tags(META_TAG)

    For Each element In metaElements
        If element.Name = META_NAME Then
            kwd = element.Content
        End If
    Next

    MsgBox kwd

End Sub