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

使用Colly如何提取嵌套在HTML元素属性内的JSON字段productId

解决方法

问题原因

productId不是<button>元素的独立HTML属性,它是data-product属性值(JSON字符串)中的嵌套字段,你直接通过ChildAttr抓取productId属性自然没有返回结果。

操作步骤

  1. 先按你现有的逻辑拿到完整的data-product JSON字符串
  2. 引入Go标准库encoding/json,将JSON字符串反序列化为结构体/Map,即可提取到目标productId

代码示例

方法1:提前定义结构体(推荐,类型安全)

import "encoding/json"

// 定义结构体,仅需声明你需要的字段即可
type ProductMeta struct {
    ProductId string `json:"productId"`
    // 其他需要用到的字段可以按JSON结构补充
}

// 你的Colly逻辑部分
dataProductStr := h.ChildAttr("span.info>button", "data-product")
var productMeta ProductMeta
err := json.Unmarshal([]byte(dataProductStr), &productMeta)
if err != nil {
    // 可按需添加错误处理逻辑
    println("JSON解析失败:", err.Error())
    return
}
// 取到目标productId
targetProductId := productMeta.ProductId

方法2:用Map接收(无需提前定义结构)

import "encoding/json"

dataProductStr := h.ChildAttr("span.info>button", "data-product")
var productMap map[string]interface{}
err := json.Unmarshal([]byte(dataProductStr), &productMap)
if err != nil {
    println("JSON解析失败:", err.Error())
    return
}
// 类型断言后取值
targetProductId := productMap["productId"].(string)

注意事项

你贴出的HTML示例中data-product的JSON双引号没有转义,实际正常的网页返回中该属性内的双引号会被转义为&quot;,Colly读取属性时会自动将其转回普通双引号,无需你额外做转义处理,可直接用于JSON解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:57:02