我经常使用下面的函数变体来处理诸如从网页中提取 html 或通过查询 API 得到 JSON 结果等等。
后期版本
这个“独立”版本不需要参考:
Public Function getHTTP(ByVal url As String) As String
'returns HTML from URL (works on *almost* any URL you throw at it)
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", url, False
.Send
getHTTP = StrConv(.responseBody, vbUnicode)
End With
End Function
早订版
如果您要访问多个网站,则改用此版本会更高效(速度提高两倍,并且更容易占用系统资源)。您需要添加对 MS XML 库的引用(Tools → References → Microsoft XML, v6.0)。
Public Function getHTTP(ByVal url As String) As String
'Returns HTML from a URL, early bound (requires reference to MS XML6)
Dim msXML As New XMLHTTP60
With msXML
.Open "GET", url, False
.Send
getHTTP = StrConv(.responseBody, vbUnicode)
End With
Set msXML = Nothing
End Function
只返回文本
当使用上述函数调用网页时,它们将返回原始 HTML 源代码。您可以剥离 HTML 标记,只留下带有来自Tim Williams 的这个漂亮功能的页面的“纯文本”版本:
Function HtmlToText(sHTML) As String
'requires reference: Tools → References → "Microsoft HTML Object Library"
Dim oDoc As HTMLDocument
Set oDoc = New HTMLDocument
oDoc.body.innerHTML = sHTML
HtmlToText = oDoc.body.innerText
End Function
示例:
综合起来,下面的例子返回“this”网页的纯文本。
Option Explicit
'requires reference: Tools > References > "Microsoft HTML Object Library"
Function HtmlToText(sHTML) As String
Dim oDoc As HTMLDocument
Set oDoc = New HTMLDocument
oDoc.body.innerHTML = sHTML
HtmlToText = oDoc.body.innerText
End Function
Public Function getHTTP(ByVal url As String) As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", url, False
.Send
getHTTP = StrConv(.responseBody, vbUnicode)
End With
End Function
Sub Demo()
Const url = "https://stackoverflow.com/questions/54670251"
Dim html As String, txt As String
html = getHTTP(url)
txt = HtmlToText(html)
Debug.Print txt & vbLf 'Hit CTRL+G to view output in Immediate Window
Debug.Print "HTML source = " & Len(html) & " bytes"
Debug.Print "Plain Text = " & Len(txt) & " bytes"
End Sub
更多信息: