首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用goquery提取元描述字段

用goquery提取元描述字段
EN

Stack Overflow用户
提问于 2015-05-27 06:43:11
回答 2查看 2.9K关注 0票数 4

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

代码语言:javascript
复制
Description field: text/html; charset=iso-8859-15
Description field: width=device-width
Description field: THIS IS THE TEXT I WANT TO EXTRACT

我已经快到了,不过我只想得到一个元字段,其中的名称是== 'description‘。不幸的是,我不知道如何将这个附加条件添加到我的代码中。

代码语言:javascript
复制
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)
    })
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-27 06:47:18

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

代码语言:javascript
复制
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()

代码语言:javascript
复制
if name, _ := s.Attr("name"); strings.EqualFold(name, "description") {
    // proceed to extract and use the content of description
}
票数 10
EN

Stack Overflow用户

发布于 2021-10-06 20:23:44

代码语言:javascript
复制
    attr, _ := doc.Find("meta[name='description']").Attr("content")
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30474991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档