我正在使用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)
})
}发布于 2015-05-27 06:47:18
只需检查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
}发布于 2021-10-06 20:23:44
attr, _ := doc.Find("meta[name='description']").Attr("content")https://stackoverflow.com/questions/30474991
复制相似问题