excel - 使用 VBA 从 DIV 检索数据

标签 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

最佳答案

根据您提供的内容,在我看来,您不需要为 nodeList1 建立单独的循环。只需放入第一个循环并始终引用 nodeList10 索引即可。

Dim sNode1 As String

With ThisWorkbook.Worksheets("Sheet1")

    'This nodeList is retrieving the values inside the DIV class="a69"
    'it's a list of products

    sNode1 = NodeList1.Item(0).innerText

    For i = 0 To NodeList.Length - 1

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

    Next

End With

关于excel - 使用 VBA 从 DIV 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53220468/

相关文章:

arrays - Excel如何在没有VBA的情况下从逗号分隔列表中查找所有匹配元素的行

vba - 如何在打开时自动运行多个 VBA 宏

excel - 如何将代码更改保存到 Excel VBA 加载项?

excel - Windows 7 和 Office 2007 中的办公自动化挂起

vba - Excel+VBA 如何使用自己的内容设置单元格的背景颜色?

vba - 在 Excel 中通过 VBA 发布文档

excel - 保存时出现运行时错误 1004 (Thisworkbook.save) 在一台机器上工作,而不是在另一台机器上工作

vba - for循环删除行不起作用,需要多次运行宏

java - 错误: Type mismatch: cannot convert from HSSFWorkbook to Workbook

excel - 如何在Excel中获取分隔符后的第n个文本