html - 如何使用 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
我知道这与我的“元素”有关,而且我看过他们谈论使用“孩子”或“兄弟姐妹”的视频。有关如何解决此问题的建议?
解决方案
您使用了错误的类名,因此选择了标题而不是表格。您可以使用 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
阅读:
推荐阅读
- java - 如何使用appium在移动应用程序中自动支付卡?
- javascript - Angular js 错误:$parse:syntax 语法错误
- .htaccess - 301 重定向在目标 url 的末尾添加了一个额外的单词
- php - 使用数组通过php发送短信
- pentaho - Pentaho 转换“执行 SQL 语句”与“表输入”步骤
- r - 使用 r 将名为 Natco 的新列添加到合并的 excel 文件中
- java - MySQL 8.0.11 抛出 CLIENT_PLUGIN_AUTH 是必需的
- azure - 如何拒绝订阅级别贡献者角色对 Azure 中特定资源组的访问
- perl - 使用 PERL 将 KB、MB、GB、TB 转换为 KB
- delphi - 无法从 Indy TIdCookieManager 获取 cookie