3

我正在使用goquery包从网页中提取信息。请在下面查看我的代码。运行函数后的结果是:

Description field: text/html; charset=iso-8859-15
Description field: width=device-width
Description field: THIS IS THE TEXT I WANT TO EXTRACT

我快到了,但是我只想获取名称 == 'description' 的元字段。不幸的是,我不知道如何将这个额外的条件添加到我的代码中。

func ExampleScrapeDescription() {
    htmlCode :=
        `<!doctype html>
<html lang="NL">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-15">
        <meta name="viewport" content="width=device-width">
        <meta name="description" content="THIS IS THE TEXT I WANT TO EXTRACT">
        <title>page title</title>
    </head>
    <body class="fixedHeader">
        page body
    </body>
</html>`

    doc, err := goquery.NewDocumentFromReader(strings.NewReader((htmlCode)))
    if err != nil {
        log.Fatal(err)
    }

    doc.Find("meta").Each(func(i int, s *goquery.Selection) {
        description, _ := s.Attr("content")
        fmt.Printf("Description field: %s\n", description)
    })
}
4

2 回答 2

9

只需检查name属性的值是否匹配"description"

doc.Find("meta").Each(func(i int, s *goquery.Selection) {
    if name, _ := s.Attr("name"); name == "description" {
        description, _ := s.Attr("content")
        fmt.Printf("Description field: %s\n", description)
    }
})

您可能希望以name不区分大小写的方式比较属性的值,因为您可以使用strings.EqualFold()

if name, _ := s.Attr("name"); strings.EqualFold(name, "description") {
    // proceed to extract and use the content of description
}
于 2015-05-27T06:47:18.473 回答
2
    attr, _ := doc.Find("meta[name='description']").Attr("content")
于 2021-10-06T20:23:44.343 回答