【问题标题】:Extract meta description field with goquery使用 goquery 提取元描述字段
【发布时间】:2015-05-27 06:43:11
【问题描述】:

我正在使用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)
    })
}

【问题讨论】:

    标签: go extract meta goquery


    【解决方案1】:

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

    【讨论】:

    • 谢谢,你帮了我很多忙!
    【解决方案2】:
        attr, _ := doc.Find("meta[name='description']").Attr("content")
    

    【讨论】:

    • 虽然此代码可能会回答问题,但如果您在答案中添加对其工作原理的解释,其他人会更容易理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2016-10-26
    • 1970-01-01
    • 2010-10-27
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多