You need to enable JavaScript to run this app. 使用XMLHTTP请求无法从页面style属性提取食谱图片链接
优惠活动
大模型
产品
解决方案
定价
更多

使用XMLHTTP请求无法从页面style属性提取食谱图片链接

问题原因

你取内联样式的方式和MSHTML的实现不兼容:MSHTML的HTMLDocument中调用getAttribute("style")不会返回style属性的原始字符串,而是返回样式对象,直接输出这个对象时只会得到默认属性值(也就是你看到的background-image),拿不到完整的样式内容。

解决方法
  • 不要用getAttribute("style"),直接通过元素的style.cssText属性获取完整的内联样式字符串,这是MSHTML里可靠获取内联样式的方式。
  • 图片链接嵌套在background-image: url(xxx)的格式里,拿到css文本后需要用正则提取纯图片链接。
修改后的代码
Sub GrabImageLink()
    Const Url$ = "https://www.yumm.ca/en/recipe/salmon-green-curry-1"
    Dim HTML As HTMLDocument, Http As Object
    Dim recipeVisual As HTMLHtmlElement
    Dim styleStr As String, reg As Object, matches As Object
    
    Set HTML = New HTMLDocument
    Set Http = CreateObject("MSXML2.XMLHTTP")

    With Http
        .Open "Get", Url, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
        .send
        HTML.body.innerHTML = .responseText
    End With
    
    ' 定位目标元素
    Set recipeVisual = HTML.querySelector(".recipe-visual")
    ' 直接获取完整css文本,替换原有getAttribute("style")的调用
    styleStr = recipeVisual.style.cssText
    
    ' 后期绑定正则,无需额外添加引用
    Set reg = CreateObject("VBScript.RegExp")
    reg.Global = True
    ' 匹配url()格式的内容,兼容单/双引号、无引号的写法
    reg.Pattern = "url\(['""\s]?(.*?)['""\s]?\)"
    
    Set matches = reg.Execute(styleStr)
    If matches.Count > 0 Then
        ' 输出提取到的图片链接
        Debug.Print matches(0).SubMatches(0)
    Else
        Debug.Print "未在目标元素的style中找到图片链接"
    End If
End Sub
补充说明
  • 如果运行后styleStr为空,说明你选中的.recipe-visual元素本身没有内联样式,可以先打印styleStr确认内容,再调整选择器(比如选择子元素.recipe-visual > div等,根据实际页面结构调整)。
  • 这个写法兼容大多数页面内联背景图的提取,不需要手动处理样式字符串的拼接问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 21:15:04