簡體   English   中英

如何使用 Excel VBA 解析 HTML 數據

[英]How to parse HTML data using Excel VBA

我是使用 excel VBA 解析 HTML 數據的新手。 下面是我的代碼和一些示例 HTML。 HTML 中的注意事項:pt-DefaultParagraphFont-000016">oles and Responsibilities

我想打開數百個類似的內部網頁,找到角色和職責部分,然后開始抓取某些數據並將其粘貼到各個列中。

我已經修改了下面的代碼,它現在可以根據推薦的內容工作。

順便說一句,以防萬一這對其他人有幫助,我確實發現了一個很好的修復“對象調用已斷開連接”錯誤的方法; 這是修復:設置 ie = New InternetExplorerMedium

Option Explicit
Enum READYSTATE
READYSTATE_UNINITIALIZED = 0
READYSTATE_LOADING = 1
READYSTATE_LOADED = 2
READYSTATE_INTERACTIVE = 3
READYSTATE_COMPLETE = 4
End Enum

Sub ImportStackOverflowData()
    Dim a As String
    Dim i As Long
    Dim ie As InternetExplorer
    Dim html As HTMLDocument

    'Set ie = New InternetExplorer 'replaced with InternetExplorerMedium to fix error
    Set ie = New InternetExplorerMedium 'this fixes this error: The object invoked has disconnected from its client
    ie.Visible = False
    ie.navigate "policy.myurl.com"
    Do While ie.READYSTATE <> READYSTATE_COMPLETE
        DoEvents
    Loop
    Set html = ie.document

    Dim tag As IHTMLElement
    Dim tags As IHTMLElementCollection
    Set tags = html.getElementsByClassName("pt-000015")
    For Each tag In tags
        'more logic here
    Next

    Set html = ie.document
    Set ie = Nothing
End Sub

HTML 示例:

div class="pt-000015"><p dir="ltr" class="pt-PolicyMajorSectionHead"><span class="pt-DefaultParagraphFont-000016">R</span><a id="Roles" class= "pt-000002"></a><span class="pt-DefaultParagraphFont-000016">角色和職責</span></p></div><p dir="ltr" class="pt-Normal "><span class="pt-000000"> </span></p><p dir="ltr" class="pt-Policy1stLevelSubhead"><span class="pt-DefaultParagraphFont-000005"><b>關鍵數據治理角色</b></span><a id="56GeneralSectionTitle_Optional_L2" class="pt-000002"></a></p><a id="56GeneralSectionTitle_Optional_L2" class="pt-000002"> </a><p dir="ltr" class="pt-PolicyText-000006"><span class="pt-DefaultParagraphFont-000007">數據治理是一項共同的責任。</span><

你需要

html.getElementsByClassName("pt-000015")

它是復數形式,返回一個集合,最后需要 Name。

暫無
暫無

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

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