使用Colly如何提取嵌套在HTML元素属性内的JSON字段productId
解决方法
问题原因
productId不是<button>元素的独立HTML属性,它是data-product属性值(JSON字符串)中的嵌套字段,你直接通过ChildAttr抓取productId属性自然没有返回结果。
操作步骤
- 先按你现有的逻辑拿到完整的
data-productJSON字符串 - 引入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双引号没有转义,实际正常的网页返回中该属性内的双引号会被转义为",Colly读取属性时会自动将其转回普通双引号,无需你额外做转义处理,可直接用于JSON解析。
内容的提问来源于stack exchange,提问作者Sinan A
相关产品推荐
相关产品推荐

