首页 > 解决方案 > 如何使用 VBA 从 HTML 标记中提取值以在 Excel 中使用?

问题描述

片段摘要:(第一个li-tag打开显示内容,其他li-tag相同,只是dd-tags中的值不同。

<body id=“WEBSITE“&gt;
 <div> id="layout" class="  MAIN SECTION "</div>
  <main>
  <ul id=“RESULTS“&gt;
  <li class="content" style="position:relative;">
  <dl>
   <dt class="first">HEAD01:</dt>
   <dd>VALUE01</dd>
   <dt class="first"> HEAD02:</dt>
   <dd> VALUE02</dd>
   <dt class="first"> HEAD03:</dt>
   <dd> VALUE03</dd>
   <dt class="first"> HEAD04:</dt>
   <dd> VALUE04</dd>
  </dl>
 </li>
<li class="content" style="position:relative;">… </li>
 <li class="content" style="position:relative;">… </li>
 <li class="content" style="position:relative;">… </li>
 <li class="content" style="position:relative;">… </li>
</ul>
</main>
</body>

li-tag包含一个对象的不同属性,每个对象具有相同的头 HEAD01、02、03 和 04(在“dt”下),每个 li-tag 中的 VALUE 不同(在“dd”下)。我没有成功地提取标签中的值,使其在 Excel 中列为相应标题下的列值,即 Excel 表中 HEAD01 下所有 li.dd-tags 中的 Value01。

我的代码:

Public Sub GetData()

    Const url = "URL"
    Dim html As New HTMLDocument, Htmldoc As New HTMLDocument
    Dim RecsCnt As Object, x As Long
       
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False
        .send
        html.body.innerHTML = .responseText
    End With
                                   
     Set RecsCnt = html.querySelectorAll("li")
    'Set RecsCnt = html.querySelectorAll("dl")
    
    With ActiveSheet

       For x = 0 To RecsCnt.Length - 1
        .Cells(x + 2, 2) = html.querySelectorAll("dd").Item(0).innerText
       Next
        
    End With

End Sub

有没有人有一个有效的想法?谢谢

标签: htmlexcelvbaweb-scrapingqueryselector

解决方案


这应该为您提供所需的数据 - 您只需要使用格式化:

Sub Get_Text_from_website()

Dim IE As New InternetExplorer
With IE
    .Visible = True
    .navigate "https://versteigerungspool.de/amtsgericht/celle.92437/suche"
    While .Busy Or .readyState < 4: DoEvents: Wend
    Dim j As Long
    Dim element As Object, i As Long
    Set dtElements = IE.document.getElementsByTagName("dt")
    Set ddElements = IE.document.getElementsByTagName("dd")

    For Each element In dtElements
        ActiveSheet.Cells(i + 1, 1) = element.innerText
        i = i + 1
    Next

    For Each element In ddElements
        ActiveSheet.Cells(j + 1, 2) = element.innerText
        j = j + 1
    Next

    IE.Quit
End With

结束子


推荐阅读