使用goquery提取元描述字段

4
我正在使用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)
    })
}
2个回答

11

只需检查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
}

谢谢,你帮了我很多! - Rogier Lommers

3
    attr, _ := doc.Find("meta[name='description']").Attr("content")

虽然这段代码可能回答了问题,但如果您在答案中添加了它的工作原理的解释,那么其他人更容易理解。 - Ryan M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接