You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA解析WinHttpRequest返回HTML提取meta description标签方法问询

你可以通过以下两种方式提取<meta name="description">的内容:


方法1:使用HTMLDocument对象解析(推荐)

这种方法直接调用系统的HTML解析能力处理返回内容,不用手动处理字符串,容错性更强,兼容标签属性顺序变化、空格换行等情况。
你可以直接用后期绑定的方式调用,无需额外引用库,修改后的完整代码如下:

Function getSetName(ByVal setNUMBER As String) As String
    Dim oRequest As Object
    Dim htmlDoc As Object ' HTML文档对象
    Dim metaTags As Object
    Dim i As Integer
    Dim xmlResponse As String
    Dim setDescription As String
    Dim setName As String
   
    Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    oRequest.Open "GET", "https://brickset.com/sets/" & setNUMBER, False ' 第三个参数指定同步请求
    oRequest.Send
    xmlResponse = oRequest.ResponseText
    
    ' 初始化HTML解析器
    Set htmlDoc = CreateObject("htmlfile")
    htmlDoc.Write xmlResponse
    htmlDoc.Close
    
    ' 提取所有meta标签
    Set metaTags = htmlDoc.getElementsByTagName("meta")
    For i = 0 To metaTags.Length - 1
        ' 匹配name属性为description的标签
        If LCase(metaTags(i).Name) = "description" Then
            setDescription = metaTags(i).Content ' 直接获取content属性值
            Exit For
        End If
    Next i
    
    ' 后续你可以从setDescription里提取需要的setName信息
    getSetName = setName ' 这里补充你自己的提取逻辑即可

End Function

如果需要更好的代码提示,可以在VBA编辑器的「工具-引用」中勾选Microsoft HTML Object Library,把htmlDoc声明为HTMLDocument类型即可。


方法2:正则表达式快速匹配

如果你只需要临时快速提取内容,也可以用正则匹配标签的content值,代码示例:
首先需要在「工具-引用」中勾选Microsoft VBScript Regular Expressions 5.5,或者用后期绑定:

' 放在原来的解析位置即可
Dim reg As Object
Set reg = CreateObject("VBScript.RegExp")
reg.Pattern = "<meta\s+name\s*=\s*""description""\s+content\s*=\s*""([^""]*)"""
reg.IgnoreCase = True ' 忽略大小写
reg.Global = False

If reg.Test(xmlResponse) Then
    setDescription = reg.Execute(xmlResponse)(0).SubMatches(0)
End If

注意这种方法对标签格式比较敏感,如果标签属性顺序调换、用单引号包裹属性值就会匹配失败,仅适合临时使用。


内容的提问来源于stack exchange,提问作者afskymonkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:36:07