VBA:从HTMLTable抓取确切的元素

时间:2019-03-05 16:38:29

标签: html vba web-scraping

请帮助我了解如何在类名a的{​​{1}}中找到标签Table

我收到bptable,但我不知道该如何解决。

Object does not support this method

2 个答案:

答案 0 :(得分:0)

您可以使用.getElementsByTagName("a")或尝试使用VidRows(0)来获取单个元素,而不是在元素集合上使用for loop,以便将.getElementsByTagName("a")应用于元素。我会选择for loop来达到目的。以下是获取内容的一种方法。

Sub ListVideosOnPage(VidCatName As String, VidCatURL As String)

    Dim XMLReq As New XMLHTTP60
    Dim HTMLDoc As New HTMLDocument
    Dim VidInnerRows As Object
    Dim R As Long

    XMLReq.Open "GET", VidCatURL, False
    XMLReq.send

    If XMLReq.Status <> 200 Then
        MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
        Exit Sub
    End If

    HTMLDoc.body.innerHTML = XMLReq.responseText
    Set XMLReq = Nothing

    For Each VidInnerRows In HTMLDoc.getElementsByClassName("bptable")
        With VidInnerRows.getElementsByTagName("a")
            If .Length Then R = R + 1: Cells(R, 1) = .Item(0).innerText
        End With
    Next VidInnerRows
End Sub

答案 1 :(得分:0)

我通常将css选择器用作更快的选择器方法,并减少循环,从而降低复杂度。您循环一个nodeList。

Dim nodeList As Object, i As long
Set nodeList = HTMLDoc.querySelectorAll(".bptable a")
For i = 0 To nodeList.Length - 1
    Debug.Print nodeList.item(i).innerText
Next

.前面的bptableclass selector;后面的空格是descendant combinator,最后的atype selector。它说,选择父级为a类的bptable个标记元素。

我正在打印到立即窗口 Ctrl + G