如何在VBA中使用HTMLDocument对象按属性名称获取标签的属性值



我想获取带有属性名称("charset")的标签("meta")的所有属性值。作为我的宏的结果,我希望看到:

1/4 element "charset" = UTF-8

但我得到:


1/2 element "charset" = UTF-8 2/2 element "charset" = UTF-8

我哪里犯了错误?

Option Explicit
Sub ParseAnAttr()
    Dim MetaTags As String, i As Integer, j As Integer
    MetaTags = ""
    MetaTags = MetaTags & "<meta charset=""UTF-8""/> "
    MetaTags = MetaTags & "<meta name=""ResourceLoaderDynamicStyles"" content=""1""/> "
    MetaTags = MetaTags & "<script type=""text/javascript""> "
    MetaTags = MetaTags & "<meta name=""generator"" content=""Media""/> "
    MetaTags = MetaTags & "<meta name=""referrer"" content=""origin""/> "
    Dim objHtml As Object
    Set objHtml = CreateObject("htmlfile")
    With objHtml
        .Open
        .write MetaTags
        .Close
    End With
    Dim objElements As Object, objElement As Object
    Set objElements = objHtml.getElementsByTagName("meta")
    For Each objElement In objElements
        If objElement > 0 Then i = i + 1
    Next objElement
    For Each objElement In objElements
        For j = 0 To i - 1
            If objElement.Charset <> "" Then
                Debug.Print j + 1 & "/" & i & " element ""charset"" = " & objElement.Charset
            End If
        Next j
    Next objElement
End Sub

<meta>标签的中间有一个未闭合的<script>元素。这是故意的吗?objElement.Charset没有按照你的想法做。

试试这个:

Sub ParseAnAttr()
    Dim MetaTags As String, att
    Dim objHtml As Object
    Dim objElements As Object, objElement As Object, j As Long
    MetaTags = "<meta charset=""UTF-8""/> " & _
        "<meta name=""ResourceLoaderDynamicStyles"" content=""1""/> " & _
        "<script type=""text/javascript"" ></script> " & _
        "<meta name=""generator"" content=""Media""/> " & _
        "<meta name=""referrer"" content=""origin""/> "
    Set objHtml = CreateObject("htmlfile")
    With objHtml
        .Open
        .write MetaTags
        .Close
        Set objElements = .getElementsByTagName("meta")
    End With
    j = 1
    For Each objElement In objElements
        att = objElement.getAttribute("charset")
        If att <> "" Then
            Debug.Print objElement.outerHTML
            Debug.Print j + 1 & "/" & objElements.Length & " element ""charset"" = " & att
        End If
        j = j + 1
    Next objElement
End Sub

最新更新