使用VBA从DIV检索数据

时间:2018-11-09 05:44:11

标签: excel vba excel-vba

我有这个工作代码,可以用来从DIVS内部获取数据。

在此示例中,我将“水果”作为类别。

我想获得所有水果,并在其旁边添加类别的名称。

HTML看起来像这样

 <DIV style="HEIGHT:100%;WIDTH:100%" ID="oReportDiv">
     <DIV class="a69"> Fruits  </DIV>

     <DIV style="word-wrap:break-word;text-decoration:none;" 
          class="a92">Banana</DIV>
     <DIV style="word-wrap:break-word;text-decoration:none;" 
          class="a92">Mango</DIV>
     <DIV style="word-wrap:break-word;text-decoration:none;"  
          class="a92">Apple</DIV>
 </DIV>

执行代码会产生:

       Banana         Fruit
       Mango 
       Apple

但是我需要的是:

       Banana         Fruit
       Mango          Fruit
       Apple          Fruit

我该如何实现?

更新:我忘了发布代码了

        t = Timer
    Do
        DoEvents
        On Error Resume Next


        Set nodeList = .document.querySelectorAll("#oReportCell .a92")
        Set nodeList1 = .document.querySelectorAll("#oReportCell .a69")

        On Error GoTo 0
        If Timer - t > MAX_WAIT_SEC Then Exit Do

    Loop While nodeList Is Nothing

    If Not nodeList Is Nothing Then

        With ThisWorkbook.Worksheets("Sheet1")

        'This nodeList is retrieving the values inside the DIV class="a69"
        'it's a list of products
            For i = 0 To nodeList.Length - 1

              .Cells(i + 1, 1) = nodeList.Item(i).innerText

            Next
        'This nodeList1 is retrieving the value inside the DIV class="a92"
        'it's the name of the product (so only one value)
           For i = 0 To nodeList1.Length - 1

               .Cells(i + 1, 8) = nodeList1.Item(i).innerText

           Next

        End With
    End If

1 个答案:

答案 0 :(得分:2)

根据您提供的内容,在我看来,nodeList1不需要单独的循环。只需将其放在第一个循环中,并始终引用0的{​​{1}}索引即可。

nodeList1