我需要创建一个 VBA 宏,它采用特定网站并搜索 ID。找到 ID 后,我需要获取文本并将其复制到 Excel 中。
这是网站的源代码:
<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>
我需要“pre”之间的文本
这是我在 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”,也尝试过使用 Element As String 但它也没有用。
如果有人可以帮助我完成我的代码,那就太棒了:D
最佳答案
文本不在属性中,而是在 pre
元素中。所以 getAttribute
函数无法返回所需的文本。
如果您想获取第一个文本,请查看函数 querySelector
。此函数返回 IHTMLElement
并接受 selector .
如果您希望返回所有文本,请尝试函数 querySelectorAll
。此函数返回 IHTMLDOMChildrenCollection
并接受 selector以及。
示例:
' 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
关于html - 使用 VBA 从网站获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40485914/