html - 使用 VBA 从网站获取文本

标签 html vba internet-explorer dom web-scraping

我需要创建一个 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/

相关文章:

html - 我无法将网站顶部的白色栏移走

excel - 将 csv 文件导入 Excel 非事件工作表的宏

html - 使用 :hover and :hover:first-letter 时,CSS 动画在 IE 中不起作用

java - IE 11 中的 Adob​​e PDF 灰屏

javascript - 我正在尝试 .Find() Div 中的 TextArea

html - CSS 溢出 : Force one div to overflow

php获取网站主机

arrays - 基于值突出显示单元格,多重搜索数组

excel - 减去时间

javascript - ie9 中的 Angular js 问题