将特定的HTMLElement添加到HTMLElementCollection

时间:2020-06-24 16:55:12

标签: vba web-scraping mshtml

我不是一个非常有经验的编码人员,所以我试图创建一个不需要非常强大/雄辩的网络抓取工具。我的问题是,我可以从特定网站上抓取数据的唯一方法是使用每个SHTMLelement的ID。然后,我想将所有这些元素放入一个元素集合中,但是我不知道该怎么做。这是我的代码:

    Dim IE As New SHDocVw.InternetExplorerMedium
    
    Dim HTMLDoc As MSHTML.HTMLDocument
    Dim HTMLgrades As MSHTML.IHTMLElementCollection ' The collection I want to make
    Dim HTMLgrade1 As MSHTML.IHTMLElement
    Dim HTMLgrade2 As MSHTML.IHTMLElement
    Dim HTMLgrade3 As MSHTML.IHTMLElement  'there are 100's of grades, but I will just use three here
    
    IE.Visible = True
    IE.navigate "website I am navigating to"
   
    ' waiting mechanism for website to load

    Set HTMLDoc = IE.Document
    Set HTMLgrade1 = HTMLDoc.getElementById("longidname_1")
    Set HTMLgrade2 = HTMLDoc.getElementById("longidname_2")
    Set HTMLgrade3 = HTMLDoc.getElementById("longidname_3")

我尝试了所有类型的代码来将每个元素添加到elementcollection中,但是我一直遇到错误。我知道最有可能提供一种超级简单的解决方案,因此,我感谢能获得的任何帮助!

1 个答案:

答案 0 :(得分:0)

例如:

Dim IE As New SHDocVw.InternetExplorerMedium

Dim HTMLDoc As MSHTML.HTMLDocument
Dim col As New Collection, arr, id
 
IE.Visible = True
IE.navigate "website I am navigating to"

' waiting mechanism for website to load

arr = Array("longidname_1", "longidname_2", "longidname_3")
For Each id In arr
    col.Add HTMLDoc.getElementById(id)
Next