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

VBA Selenium提取商品规格不完整,请求完整提取方案

解决商品规格提取不全(被Read More隐藏)的VBA方案

你遇到的问题是网页中部分商品规格被折叠在「Read More」区域内,默认处于不可见状态,直接调用FindElementsByCss只能获取到页面加载时可见的元素,隐藏区域内的元素虽然class一致,但文本未被渲染,导致提取时只显示冒号。

修改后的完整代码

Sub All_Specs_Extract()
    Dim chr As New Selenium.ChromeDriver
    chr.Timeouts.ImplicitWait = 10
    chr.Start

    Dim ws As Worksheet, row As Long, lastRow As Long, col As Long
    Set ws = ThisWorkbook.Sheets(1)
    row = 2
    lastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).row

    For row = 2 To lastRow
        ' 加载目标网页
        Dim MyURL As String
        MyURL = ws.Cells(row, 1)
        chr.Get MyURL
        ' 等待页面完全加载
        chr.WaitUntil DocumentReadyState Is Complete
        
        ' 关键步骤:点击Read More展开隐藏的规格内容
        On Error Resume Next ' 处理部分页面没有Read More的情况
        chr.FindElementByCss("button[aria-expanded='false']").Click ' 定位Read More按钮并点击
        On Error GoTo 0
        
        ' 等待隐藏内容加载完成
        chr.Wait 2 ' 可根据网页加载速度调整等待时间
        
        ' 获取所有规格标签和对应值
        Dim specs As Selenium.WebElements
        Dim values As Selenium.WebElements
    
        Set specs = chr.FindElementsByCss("p.snippet.product-detail-page-component_label__3S-Gu")
        Set values = chr.FindElementsByCss("p.snippet.product-detail-page-component_value__2ZiIc")       
        For col = 1 To specs.Count
            ' 处理值为空的情况,避免只显示冒号
            Dim specText As String, valueText As String
            specText = specs.Item(col).Text
            valueText = values.Item(col).Text
            ws.Cells(row, col + 1).Value = specText & ":" & IIf(valueText = "", "无", valueText)
        Next col
    Next row
    chr.Quit
 End Sub

核心修改说明

  1. 展开隐藏内容:通过定位「Read More」按钮(使用CSS选择器button[aria-expanded='false'],可根据实际网页调整)并点击,让所有规格内容变为可见状态。如果按钮文本是「Read More」,也可以用chr.FindElementByXPath("//button[contains(text(),'Read More')]").Click定位。
  2. 错误处理:添加On Error Resume Next避免因部分页面没有折叠按钮导致代码报错中断。
  3. 等待优化:使用chr.WaitUntil DocumentReadyState Is Complete替代手动循环判断,点击后增加短暂等待确保隐藏内容完全渲染。
  4. 空值处理:用IIf函数处理值为空的情况,避免单元格只显示冒号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:27:30