簡體   English   中英

Excel VBA 宏獲取 HTML SPAN ID 值

[英]Excel VBA macro to get HTML SPAN ID value

我很欣賞有類似的問題,但作為一個新手,我發現很難完全適應示例。

問題陳述我希望在 Excel 中創建一個宏來提取網站https://www.centralbank.ae/en/fx-rates上的“最后更新”值。 具體來說,這可以在他們的 HTML 代碼中找到(值示例也在下面):

<span class="dir-ltr">11 Feb 2021 6:00PM</span>

我想改變用途這里的代碼( https://www.encodedna.com/excel/extract-contents-from-html-element-of-a-webpage-in-excel-using-vba.htm )似乎是一種在后台啟動 IE 然后清除所有元素的非常干凈的方法。 它遍歷我不需要做的超鏈接。

我的代碼似乎不起作用:

    Option Explicit

Const sSiteName = "https://www.centralbank.ae/en/fx-rates"

Private Sub GetHTMLContents()
    ' Create Internet Explorer object.
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = False          ' Keep this hidden.
    
    IE.navigate sSiteName
    
    ' Wait till IE is fully loaded.
    While IE.readyState <> 4
        DoEvents
    Wend
    
    Dim oHDoc As HTMLDocument     ' Create document object.
    Set oHDoc = IE.document
    
    Dim oHEle As HTMLSpanElement     ' Create HTML element (<span>) object.
    Set oHEle = oHDoc.getElementById("dir-ltr").innerText ' Get the element ref using its ID. [A]
    

    
    ' Clean up.
    IE.Quit
    Set IE = Nothing
    Set oHEle = Nothing
    Set oHDoc = Nothing
End Sub

一旦它可以打印到innerText ,我認為您可以將 [A] 注釋的行替換為類似的內容,但再次不能 100% 確定如何替換:

Cells(iCnt + 1, 1) = .getElementsByTagName("h1").Item(iCnt).getElementsByTagName("a").Item(0).innerHTML

目標是將此 SPAN CLASS ID 值打印到 Excel 工作表(例如“Sheet1”)中的單元格中。

span 標簽沒有 ID。 dir-ltr是 class。 您可以使用getElementsByClassName()獲取具有特定 class 的所有元素。 使用帶有復數Elementget 方法,您可以創建一個基於索引 0 的節點集合。 class dir-ltr是文檔中唯一具有此名稱的 class 。

您可以通過索引 0 引用它,該索引將寫在節點集合的名稱后面(如數組)或方法調用后面。 如果在方法調用之后執行此操作,節點集合將立即被銷毀,但您將獲得列表的索引元素。

如果你想閱讀內文,你可以直接在索引后面進行,但你有一個字符串,沒有innertext 我在以下代碼中使用了它:

Private Sub GetHTMLContents()
  
  Const sSiteName = "https://www.centralbank.ae/en/fx-rates"
  Dim IE As Object
  
  'Create Internet Explorer object.
  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = False ' Keep this hidden.
  IE.navigate sSiteName
  
  ' Wait till IE is fully loaded.
  While IE.readyState <> 4: DoEvents: Wend
  
  'New sheet with name "New sheet" at the end
  ThisWorkbook.Sheets.Add after:=Sheets(Worksheets.Count)
  ThisWorkbook.ActiveSheet.Name = "New sheet"
  
  ' Get the element ref using its ID. [A]
  ThisWorkbook.Sheets("New sheet").Cells(1, 1) = IE.document.getElementsByClassName("dir-ltr")(0).innerText
  
  ' Clean up.
  IE.Quit
  Set IE = Nothing
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM