0

我有一个问题,即不同的网站需要在循环中使用不同类型的 QuerySelector(即GetElementsByClassNameGetElementsByTagNamequerySelectorAll等)才能返回结果。

就目前而言,如果我在“Set list = html.querySelectorAll(ID)”行使用硬编码的 FIX SELECTOR,则此代码可用于检索网站信息,但如果我尝试使其基于 VARIABLE,则它不起作用在循环中的工作表行属性 query.name 上。

我不确定这是否只是分配了正确的变量类型,但我只是不知道如何处理使这部分工作......

Sub FETCHER()
    Dim URL As String, tag As String, ID As String, LastRow As Integer, j As Long
    Dim html As HTMLDocument, list As Object, i As Long

    Dim xmlhttp As Object
    Set xmlhttp = CreateObject("MSXML2.XMLHTTP.6.0")
    'CreateObject("WINHTTP.WinHTTPRequest.5.1")

    Worksheets("TEST").Activate
    LastRow = Range("C" & Rows.Count).End(xlUp).Row

    For j = 2 To LastRow
        With ActiveSheet
            URL = Range("S" & j).Text            'URL = https://stackoverflow.com/
            tag = Range("T" & j).Text            'TAG = getElementsByClassName '<--- Where I want to assign the selector type (i.e. getelementsbyclassname, getelementsbytagname, etc.)
            ID = Range("U" & j).Text             'Element ID = "CONTENT"
        End With

        Set xmlhttp = New MSXML2.XMLHTTP60
        Set html = New HTMLDocument

        With xmlhttp
            .Open "GET", URL, False
            .setRequestHeader "User-Agent", "Chrome/39.0.2171.95"
            .Send

            html.body.innerHTML = .responseText
        End With

        'Set list = html.querySelectorAll("CONTENT")   <---Example..
        Set list = html.querySelectorAll(ID)          '<---This WORKS as it's HARD-CODED
        Set list = html.TAG(ID)                       '<---This DOESN'T WORK in trying to make it VARIABLE

        For i = 0 To 5
            With ActiveSheet
                .Cells(j, 22 + i) = list.Item(i).innerText
                '.Cells(j + 1, 22 + 1) = list.Item(i).getAttribute("href")
            End With
        Next
    Next
End Sub

任何帮助将不胜感激!

4

1 回答 1

2

我认为您正在尝试通过字符串变量调用方法,在这种情况下您需要 CallByName 例如

Option Explicit
Public Sub test()
    Dim xmlhttp  As MSXML2.XMLHTTP60
    Dim html As MSHTML.HTMLDocument

    Set xmlhttp = New MSXML2.XMLHTTP60
    Set html = New MSHTML.HTMLDocument

    With xmlhttp
        .Open "GET", "https://stackoverflow.com/", False
        .setRequestHeader "User-Agent", "Chrome/39.0.2171.95"
        .send
        html.body.innerHTML = .responseText
    End With

    Dim tag As String, list As Object

    tag = "GetElementsByTagName"
    Set list = CallByName(html, tag, VbMethod, "a") '<==note the args at end e.g. here the element type selector of "a" for a tag elements.
    Debug.Print list.Length
End Sub

你不能使用object.[string variable for method]

于 2019-10-14T07:31:38.837 回答