我正在使用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'的meta字段。不幸的是,我不知道如何在我的代码中添加这个额外条件。
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)
})
}
只需检查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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句