[英]How do I pull the second td tag from a table using Excel-VBA
I'm trying to pull the second td tag, or the US Ten Year Treasury rate from https://www.bankrate.com/rates/interest-rates/federal-funds-rate.aspx using Excel VBA.我正在尝试从https://www.bankrate.com/rates/interest-rates/federal-funds-rate.aspx使用 Excel Z6E34BZ7E6A9EEF6007 提取第二个 td 标签或美国十年期国债利率Here's what I have so far:
这是我到目前为止所拥有的:
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
I know it has something to do with my "Element", and I've seen videos where they talk about using "children" or "sibling".我知道这与我的“元素”有关,而且我看过他们谈论使用“孩子”或“兄弟姐妹”的视频。 Advice on how to fix this?
有关如何解决此问题的建议?
You are using the wrong class name and in so doing are selecting the caption rather than the table.您使用了错误的 class 名称,这样做是在选择标题而不是表格。 You can use a css class selector combined with nth-of-type to get 2nd td.
您可以使用 css class 选择器与 nth-of-type 组合来获得 2nd td。 I use one of the class values present in the table element.
我使用表格元素中存在的 class 值之一。
.Range("A2").Value = ie.document.querySelector(".table-inline td:nth-of-type(2)").innerText
As that content is static you can use a faster xhr rather than browser to retrieve value.由于该内容是 static 您可以使用更快的 xhr 而不是浏览器来检索值。 I show a variety of ways of then getting the node you want.
我展示了各种获取所需节点的方法。
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
Read about:阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.