2016-11-08 169 views
1

我需要創建一個VBA宏,它需要一個特定的網站並搜索該ID。找到ID時,我需要將文本複製到Excel中。用VBA從網站獲取文本

這裏是網站的源代碼:

<tr> 
<td style="width: 10%; color: blue" valign="top"><a name="111" id="111">111</td> 
<td><pre> 
    Some text I Need in excel 
</pre></a><td> 
</tr> 

我需要 「預」 之間的文本

這是我在VBA嘗試:

Set IE = CreateObject("InternetExplorer.Application") 
IE.Visible = True 
IE.Navigate Website_URL 

Do While IE.Busy And Not IE.readyState = READYSTATE_COMPLETE 
    DoEvents 
Loop 
Set Document = IE.Document 

Dim SearchValue As String 
Set Element = Document.getElementById(SearchValue).getAttribute("pre") 

Range("I1").Select 
ActiveCell.FormulaR1C1 = Element 

我也試過,而不是「.getAttribute」其他方法,並試圖使用元素作爲一個字符串,但它也沒有工作。

這將是真棒,如果有人可以幫助我與我的代碼:d

回答

0

文本並不位於屬性,但在pre元素。所以getAttribute函數不能返回所需的文本。

看看功能querySelector如果你想獲得第一個文本。此函數返回IHTMLElement並接受selector

如果您希望返回所有文本,請嘗試功能querySelectorAll。該函數返回IHTMLDOMChildrenCollection並接受selector。 HTH


例子:

' Add reference to Microsoft Internet Controls (SHDocVw) 
' Add reference to Microsoft HTML Object Library 

Dim selector As String 
' select element with id = SearchValue which has td which has pre 
selector = "#" & SearchValue & " td pre" 

Dim onePre As IHTMLElement 
Set onePre = doc.querySelector(selector) 
If Not onePre Is Nothing Then 
    MsgBox "First pre element text: " & onePre.innerText 
End If 

Dim allPre As IHTMLDOMChildrenCollection 
Set allPre = doc.querySelectorAll(selector) 

If allPre.Length > 0 Then 
    Dim el, text 
    For el = 0 To allPre.Length - 1 
     text = text & allPre.Item(el).innerText 
    Next 
    MsgBox "All pre elements text: " & text 
End If 

ie.Quit 
+0

這工作不錯:d感謝您的! – Wikked

+0

不客氣! – dee