【问题标题】:how to scrape attribute in attibute with colly如何用牧羊犬刮取属性中的属性
【发布时间】:2021-12-08 03:25:47
【问题描述】:

我尝试抓取产品的 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 获取这些数据?

【问题讨论】:

  • 以前没用过go-colly,不过可能是h.ChildAttr("span.info&gt;button", "data-product.productId")?
  • 谢谢,但又没有结果。我认为 colly 不重要。 goquery 或任何用于解析 html 的方法都使用相同的方法,但我无法从 google 中找到

标签: html go web-scraping html-parsing go-colly


【解决方案1】:

属性值是原始值,在本例中为 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 scrape

【讨论】:

  • @Shinan 我已经更新以反映您的更改,如果可以的话
  • 感谢您的回答和您的想法var result map[string]interface{} json.Unmarshal([]byte(body), &amp;result) fmt.Println(result["ProductId"])
猜你喜欢
  • 1970-01-01
  • 2017-11-28
  • 2017-10-13
  • 2018-01-03
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
相关资源
最近更新 更多