pull data from website using VBA excel multiple classname

后端 未结 3 1399
梦谈多话
梦谈多话 2020-12-15 13:40

I know this has been asked many times, but haven\'t seen a clear answer for looping thru a div and findind tags with the same classname.

My first question:

3条回答
  •  庸人自扰
    2020-12-15 14:21

    CSS selector:

    You could also use a CSS selector of #images img[src^='img/'].

    This says elements with id of images that contain tagname img with attribute src having value starting with 'img/'.

    The # is for id; [] for attribute; ^ for starts with; #images img, img within images.


    CSS query:


    As more than one element will be matched you would use the .querySelectorAll method of document and then loop the length of the returned nodeList.

    VBA Code:

    Option Explicit
    Public Sub test()
        Dim html As HTMLDocument
        Set html = New HTMLDocument
    
        With CreateObject("WINHTTP.WinHTTPRequest.5.1")
            .Open "GET", "http://www.someurl.com", False
            .send
            html.body.innerHTML = .responseText
        End With
    
        Dim aNodeList As Object, iItem As Long
        Set aNodeList = html.querySelectorAll("#images img[src^='img/']")
        With ActiveSheet
            For iItem = 0 To aNodeList.Length - 1
                .Cells(iItem + 1, 1) = aNodeList.item(iItem).innerText
                '.Cells(iItem + 1, 1) = aNodeList(iItem).innerText '<== or potentially this syntax
            Next iItem
        End With
    End Sub
    

提交回复
热议问题