![](/img/trans.png)
[英]Retreiving <TD> tag from table on website using VBA and put into excel
[英]How do I pull the second td tag from a table using Excel-VBA
我正在嘗試從https://www.bankrate.com/rates/interest-rates/federal-funds-rate.aspx使用 Excel Z6E34BZ7E6A9EEF6007 提取第二個 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
我知道這與我的“元素”有關,而且我看過他們談論使用“孩子”或“兄弟姐妹”的視頻。 有關如何解決此問題的建議?
您使用了錯誤的 class 名稱,這樣做是在選擇標題而不是表格。 您可以使用 css class 選擇器與 nth-of-type 組合來獲得 2nd td。 我使用表格元素中存在的 class 值之一。
.Range("A2").Value = ie.document.querySelector(".table-inline td:nth-of-type(2)").innerText
由於該內容是 static 您可以使用更快的 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
閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.