Html 使用VBA从网站获取文本
我需要创建一个VBA宏,它获取特定网站并搜索ID。找到ID后,我需要获取文本并将其复制到Excel中 以下是Webiste的源代码:Html 使用VBA从网站获取文本,html,vba,internet-explorer,dom,web-scraping,Html,Vba,Internet Explorer,Dom,Web Scraping,我需要创建一个VBA宏,它获取特定网站并搜索ID。找到ID后,我需要获取文本并将其复制到Excel中 以下是Webiste的源代码: <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&
<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>
我还尝试了替代“.getAttribute”的其他方法,并尝试将元素用作字符串,但也不起作用
如果有人能帮我处理代码,那就太棒了:D文本不在属性中,而是在
pre
元素中。因此getAttribute
函数无法返回所需的文本
如果要获取第一个文本,请查看函数querySelector
。此函数返回并接受IHTMlement
如果希望返回所有文本,请尝试函数querySelectorAll
。此函数返回IHTMLDOMChildrenCollection并接受。嗯
例如:
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
' 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