2014-12-22 101 views
1

我開始嘗試瞭解刮擦。我得到了這個登錄背後的頁面,我記得你不應該在通過標記名獲取元素之後嘗試執行(1),(2)或(3)的事情。但是,您應該更喜歡像Classname或ID那樣獲得更獨特的東西。但有人可以告訴我爲什麼VBA Excel Scraping

這個GetTag 工作

Dim Companyname As String 
Companyname = ie.document.getElementsByTagName("span")(1).innertext 

此的getclass 不工作

Dim Companyname As String 
Companyname = ie.document.getElementsByClassName("account-website-name").innertext 

這是我刮

文本
<span class="account-website-name" data-journey-name="true">Dwellington Journey</span> 
+2

每當您使用可能獲得更多的東西時,您需要提供一個序號索引。你在第一個例子中用**(1)**來做這件事,它引用第二個''元素(序數從零開始)。在你的第二個例子中,你忽略了序號,所以'.getElementsByClassName'不知道哪個返回,即使只有一個匹配。 – Jeeped

+0

你是老闆!謝謝! –

+0

@Jeeped這聽起來更像是一個回答而不是評論,如何充實它,將它張貼爲一個並得到你認爲值得擁有的代表? – Aiken

回答

2

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

當使用getElementsByTagNamegetElementsByClassName,等在那裏的話元素是多元的,你是返回對象的集合(如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方法使用元素(複數),而不是(單數),你是返回,如果你想治療的其中一個必須擁有的索引號附加集合集合中的元素作爲單個元素。

+0

而......那令人印象深刻。謝啦!我同意,感覺就像身份證的東西像野火一樣蔓延。在此之後,我實際上得到了4個不同的號碼,它們都具有相同的ID和classname,但在不同的父母身上。得到了所有的數字。但是再次感謝你。單個S有很大的不同。 –