首页 > 解决方案 > 如何使用 Excel-VBA 从表中提取第二个 td 标记

问题描述

我正在尝试使用 Excel VBA从https://www.bankrate.com/rates/interest-rates/federal-funds-rate.aspx提取第二个 td 标签或美国十年期国债利率。这是我到目前为止所拥有的:

Sub Ten_Year_Treasury()

' Record the US Ten Year Treasury rate from https://www.bankrate.com/rates/interest-rates/federal-funds-rate.aspx
Range("A2").ClearContents

Dim ie As InternetExplorer
Dim htmlEle As IHTMLElement

Set ie = New InternetExplorer
ie.Visible = False

ie.navigate "https://www.bankrate.com/rates/interest-rates/federal-funds-rate.aspx"

Application.Wait (Now + TimeValue("00:00:04"))

Set Element = ie.document.getElementsByClassName("table-inline__caption")

For Each htmlEle In Element

    With Sheets("10-Year Treasury")
        .Range("A2").Value = htmlEle.Children(0).innerText
    End With

Next

ie.Quit

'Remove Underline
Range("A2").Font.Underline = False
'Make Font Bold
Range("A2").Font.Bold = True

End Sub

我知道这与我的“元素”有关,而且我看过他们谈论使用“孩子”或“兄弟姐妹”的视频。有关如何解决此问题的建议?

标签: htmlexcelvbahtml-table

解决方案


您使用了错误的类名,因此选择了标题而不是表格。您可以使用 css 类选择器与 nth-of-type 组合来获得 2nd td。我使用 table 元素中存在的类值之一。

.Range("A2").Value = ie.document.querySelector(".table-inline td:nth-of-type(2)").innerText

由于该内容是静态的,您可以使用更快的 xhr 而不是浏览器来检索值。我展示了各种获取所需节点的方法。

Option Explicit

Public Sub GetInterestRate()
    Dim xhr As MSXML2.xmlhttp60, html As MSHTML.HTMLDocument
    'required VBE (Alt+F11) > Tools > References > Microsoft HTML Object Library ;  Microsoft XML, v6 (your version may vary)

    Set xhr = New MSXML2.xmlhttp60
    Set html = New MSHTML.HTMLDocument

    With xhr
        .Open "GET", "https://www.bankrate.com/rates/interest-rates/federal-funds-rate.aspx", False
        .send
        html.body.innerHTML = .responseText
    End With

    ActiveSheet.Cells(1, 1) = html.querySelectorAll(".table-inline td")(1).innerText
    'html.querySelector(".table-inline").rows(1).cells(1).innertext
    'html.querySelector(".table-inline").rows(1).children(1).innertext
    'html.querySelector(".table-inline td + td").innertext
    'html.querySelector(".table-inline td").nextsibling.innertext

End Sub

阅读:

  1. CSS 选择器
  2. xhr
  3. 下一个兄弟姐妹
  4. 查询选择器

推荐阅读