【问题标题】:Web scraping DIV class in VBAVBA 中的网页抓取 DIV 类
【发布时间】:2020-11-24 21:25:39
【问题描述】:

我在编写 VBA 代码以从网站上抓取 div 类数据并放入 Excel 时遇到了一些麻烦。由于隐私问题(患者数据),我无法发布 URL,但代码发布在下面:

<div id="location-1" class="Location">
    <div class="grid">
      <div class="row">
          <div class="info">
            <div class="column">
              <div class="element-1">[text]</div>
              <div class="element-2">[text]</div>
              <p class="element-3"></p>
              <p class="element-4">[text]</p>
              <p class="element-5"></p>
              <p class="element-6">[text]</p>
              <div class="dir">
                    <a href="[link]" class="dir" target="_blank">Get dir</a>
                  </div> 
              </div>
          </div>
      </div>
    </div>
  </div>

我的代码发布在下面。我正在尝试将“Element-1”和“Element-2”中的信息刮到每个来源的 1 行中。在这里的任何帮助将不胜感激!

Sub webscrape()
    Dim http As New XMLHTTP60
    Dim html As New HTMLdocument
    Dim source As Object
    
    With http
    .Open "get", "[link]", False
    .send
    html.body.innerHTML = .responseText
    End With
    
    For Each source In html.getElementsByClassName("column")
    x = x + 1: Cells(x, 1) = source.getAttribute("element-1")
    Cells(x, 2) = source.getAttribute("element-2")
    Next source
    
End Sub

【问题讨论】:

  • 这不是您在 vba 中获取类属性的方式。试试source.className 而不是source.getAttribute("element-1")
  • 我以为您正在尝试解析类名,如element-1element-2 等,这就是我之前的建议。

标签: html excel vba web-scraping


【解决方案1】:

这里有两种不同的解决方案。 (未测试)

第一个:

Sub webscrape()
  Dim http As New XMLHTTP60
  Dim html As New HTMLdocument
  Dim nodeColumnElements As Object
  Dim currentRow As Long
  
  currentRow = x 'Here your start row
  
  With http
    .Open "get", "[link]", False
    .send
    html.body.innerHTML = .responseText
  End With
  
  Set nodeColumnElements = html.getElementsByClassName("column")(0).getElementsByTagName("div")
  Cells(currentRow, 1) = Trim(nodeColumnElements(0).innertext)
  currentRow = currentRow + 1
  Cells(currentRow, 2) = Trim(nodeColumnElements(1).innertext)
End Sub

第二个直接抓取两个元素:

Sub webscrape()
  Dim http As New XMLHTTP60
  Dim html As New HTMLdocument
  Dim currentRow As Long
  
  currentRow = x 'Here your start row
  
  With http
    .Open "get", "[link]", False
    .send
    html.body.innerHTML = .responseText
  End With
  
  Cells(currentRow, 1) = Trim(html.getElementsByClassName("element-1")(0).innertext)
  currentRow = currentRow + 1
  Cells(currentRow, 2) = Trim(html.getElementsByClassName("element-2")(0).innertext)
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 2015-09-17
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    相关资源
    最近更新 更多