我试着抓取一个产品的productId,但我做不到。请帮帮忙
html代码
<span class="info">
<button data-product="{"merchantName":"xxx","price":"11","productName":"car window","categoryName":"windows","brandName":"aa assosiations","productId":"which I want to scrape"}">当我尝试的时候
h.ChildAttr("span.info>button", "data-product")结果为{"merchantName":"xxx","price":"11","productName":"car window","categoryName":"windows","brandName":"aa assosiations","productId":"which I want to scrape"}
当我尝试的时候
h.ChildAttr("span.info>button", "productId")没有结果。如何使用colly获取此数据?
发布于 2021-10-21 12:25:47
属性值是一个原始值,在本例中,它是JSON格式的,因此需要解析JSON才能正确获取数据。
例如:
package main
import (
"log"
"encoding/json"
"github.com/gocolly/colly"
)
func main() {
c := colly.NewCollector()
c.OnHTML(`body`, func(e *colly.HTMLElement) {
text := e.ChildAttr("span.info>button", "data-product")
var result map[string]interface{}
err := json.Unmarshal([]byte(text), &result)
if err != nil {
log.Println(err)
return
}
log.Println(result["productId"])
})
c.Visit("[some url]")
}输出
2021/10/21 14:23:24 which I want to scrapehttps://stackoverflow.com/questions/69660694
复制相似问题