送元 byProperty VS得到ELEMENTS byProperty
主要有兩種不同類型的命令來檢索網頁的.Document
一個或多個元素;那些返回單個對象和那些返回對象集合的對象。
獲取元素
當使用getElementById
,你所要求的單個對象(例如MSHTML.IHTMLElement
)。在這種情況下,可以直接檢索屬性(例如.Value
,.innerText
,.outerHtml
等)。 HTML體內不應該有多個唯一的id屬性,所以這個函數應該安全地返回i.e.document
中匹配的唯一元素。
'typical VBA use of getElementById
Dim CompanyName As String
CompanyName = ie.document.getElementById("CompanyID").innerText
警告:我注意到越來越多的網頁設計師誰似乎認爲使用多個元素相同id
是OH鍵-DOH鍵,只要ID是一樣不同的父元素中不同的<div>
元素。 AFAIK,這顯然是錯誤的,但似乎是一種日益增長的做法。使用.getElementById
時請注意返回的內容。
獲取ELEMENTS
當使用getElementsByTagName
,getElementsByClassName
,等在那裏的話元素是多元的,你是返回對象的集合(如MSHTML.IHTMLElementCollection
),即使該集合只包含一個甚至沒有。如果要使用它們直接訪問集合中某個元素的屬性,則必須提供序號索引,以便引用集合中的單個元素。這些集合中的索引號是基於零的(即第一個從(0)開始)。
'retrieve the text from the third <span> element on a webpage
Dim CompanyName As String
CompanyName = ie.document.getElementsByTagName("span")(2).innerText
'output all <span> classnames to the Immediate window until the right one comes along
'retrieve the text from the first <span> element with a classname of 'account-website-name'
Dim e as long, es as long
es = ie.document.getElementsByTagName("span").Length - 1
For e = 0 To es
Debug.Print ie.document.getElementsByTagName("span")(e).className
If ie.document.getElementsByTagName("span")(e).className = "account-website-name" Then
CompanyName = ie.document.getElementsByTagName("span")(e).innerText
Exit For
End If
Next e
'same thing, different method
Dim eSPN as MSHTML.IHTMLElement, ecSPNs as MSHTML.IHTMLElementCollection
ecSPNs = ie.document.getElementsByTagName("span")
For Each eSPN in ecSPNs
Debug.Print eSPN.className
If eSPN.className = "account-website-name" Then
CompanyName = eSPN.innerText
Exit For
End If
Next eSPN
Set eSPN = Nothing: Set ecSPNs = Nothing
總之,如果你的Internet.Explorer
方法使用元素(複數),而不是元(單數),你是返回,如果你想治療的其中一個必須擁有的索引號附加集合集合中的元素作爲單個元素。
每當您使用可能獲得更多的東西時,您需要提供一個序號索引。你在第一個例子中用**(1)**來做這件事,它引用第二個''元素(序數從零開始)。在你的第二個例子中,你忽略了序號,所以'.getElementsByClassName'不知道哪個返回,即使只有一個匹配。 – Jeeped
你是老闆!謝謝! –
@Jeeped這聽起來更像是一個回答而不是評論,如何充實它,將它張貼爲一個並得到你認爲值得擁有的代表? – Aiken