我正在寻找一种用于 Excel VBA 宏的查询,以获取 Web 页面的 HTML 源代码作为字符串。
我找到了一些使用 getHTTPrequest
的源代码,但我无法注册 .net framework system.dll
或将其链接。
谢谢!
我正在寻找一种用于 Excel VBA 宏的查询,以获取 Web 页面的 HTML 源代码作为字符串。
我找到了一些使用 getHTTPrequest
的源代码,但我无法注册 .net framework system.dll
或将其链接。
谢谢!
这是一个紧凑的函数,可以返回几乎任何指定URL的响应文本,例如网页的HTTP源代码或来自JSON API的响应文本。
Public Function getHTTP(ByVal url As String) As String
With CreateObject("MSXML2.ServerXMLHTTP.6.0")
.Open "GET", url, False: .Send
getHTTP = StrConv(.responseBody, vbUnicode)
End With
End Function
如果您需要重复调用该函数(例如在循环中),最好将其用作早期绑定函数:
Add a reference to the XML library:
Tools → References → Select Microsoft XML, v6.0
(or the highest version you have listed)
Declare a module-level variable: (place this line at the top of a module)
(Shortcut to create new VBA module: Alt + F11 → I
→ M)
Dim msXML As XMLHTTP60
Within the function, only create the XML object if the variable is not already set:
Public Function getHTTP(ByVal url As String) As String
If msXML Is Nothing Then Set msXML = New XMLHTTP60
With msXML
.Open "GET", url, False: .Send
getHTTP = StrConv(.responseBody, vbUnicode)
End With
End Function
获取此页面的HTML源代码:
Debug.Print getHTTP("https://stackoverflow.com/q/817602")
️ 注意!
许多应用程序(包括微软办公软件)现在会返回错误,如果您尝试使用此方法或其他方法(例如Excel的
WEBSERVICE
)连接到不安全的url。为避免此问题,请尽可能使用
HTTPS://
而不是HTTP://
。