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

VBA代码判断页面.stock out-of-stock类存在性失效问题排查

问题分析与修复方案

核心问题分析

  1. CSS选择器错误
    你使用的.stock out-of-stock是后代选择器,它会查找class为stock的元素下的<out-of-stock>标签元素,但实际目标是同时拥有stock和out-of-stock两个类的元素,正确的选择器应该是.stock.out-of-stock(类名之间无空格,代表元素同时具备这两个类)。

  2. querySelectorAll返回值判断逻辑错误
    querySelectorAll即使没有匹配到任何元素,也不会返回Nothing,而是返回一个长度为0的NodeList对象。因此你的If Not ohtml Is Nothing判断永远为True,导致无论商品是否缺货,函数都返回True。

  3. 语法与变量声明问题

  • 测试过程中a=getstock (txt2)的空格会引发语法问题,应改为a = getstock(txt2)。
  • 函数内的xhr、html变量未显式声明,属于隐式变量,容易引发未知错误。

修复后的代码

测试过程

Sub test()
    Dim txt1 As String
    Dim txt2 As String
    Dim a As Boolean ' 显式声明变量类型

    txt1 = "https://www.cigarsofcuba.co.uk/shop/cuban-cigars/bolivar-cigars/bolivar-belgravia-uk-regional-2015-cigars-box-of-10/"
    txt2 = "https://www.cigarsofcuba.co.uk/shop/cuban-cigars/bolivar-cigars/bolivar-belicosos-finos-cigars-box-of-25/"

    a = getstock(txt1)
    Debug.Print a ' 缺货商品应返回True

    a = getstock(txt2)
    Debug.Print a ' 有货商品应返回False
End Sub

库存检测函数

Function getstock(url As String) As Boolean
    Dim xhr As MSXML2.XMLHTTP60 ' 显式声明变量
    Dim html As MSHTML.HTMLDocument
    Dim ohtml As MSHTML.IHTMLDOMNodeList ' 指定具体类型

    Set xhr = New MSXML2.XMLHTTP60
    Set html = New MSHTML.HTMLDocument
    
    With xhr
        .Open "GET", url, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" ' 完整UA降低拦截概率
        .send
        html.body.innerHTML = .responseText
    End With
    
    ' 使用正确的CSS选择器获取匹配元素
    Set ohtml = html.querySelectorAll(".stock.out-of-stock")
 
    ' 通过NodeList长度判断是否存在缺货元素
    getstock = (ohtml.Length > 0)
End Function

额外说明

  • 可添加错误处理逻辑(如XHR请求失败的捕获),避免网络问题导致代码崩溃。
  • 部分网站会对请求进行验证,使用更贴近浏览器的User-Agent可以提升请求成功率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:06:55