**摘要:** 本文旨在解决在使用 Goquery 库抓取特定标签的网站时遇到的问题。该问题涉及将抓取到的内容输出到文件中,但输出结果为空。通过分析代码和 HTML,发现问题出在查询中,导致输出两个元素,其中第一个为空,导致文件为空。经修正后,代码能够正确地将抓取到的内容写入文件中,并打印到标准输出。
我需要抓取一个我感兴趣的标签的网站:
<script type="myjson">
[{"class": "companyname", "location"....and so on
</script>
目前我正在使用以下代码片段完成这项工作(goquery):
doc.Find("script").Each(func(i int, element *goquery.Selection) {
_, exists := element.Attr("type")
if exists {
var filepath string
filepath = "mypath"
file, err := os.Create(filepath)
if err != nil {
panic("COULD NOT CREATE FILE")
}
file.WriteString(element.Text())
fmt.Println(element.Text())
file.Close()
这段代码的问题是,虽然 element.text() 被正确打印到标准输出(它打印一个长切片,里面有几个 json,我需要将其打印到文件以供以后工作),但 file.writestring 语句不向文件打印任何内容。该文件仍为空。
看来我的查询是错误的,它输出了 2 个元素;第一个长度为零,即打印到文件的长度,第二个长度为实际内容,打印到标准输出,但不打印到文件。
您能否建议对我的代码进行更正,以便将内容正确打印到文件中?我猜我的 goquery 查询可能有错误。
正确答案
快速测试表明,只需调用 .text() 就足够了,请参阅下面的代码:
package main
import (
"fmt"
"os"
"strings"
"github.com/puerkitobio/goquery"
)
func main() {
htmlstring := `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
</head>
<body>
<h1>awesome header</h1>
<script type="myjson">
[{"class": "companyclass", "location": "companylocation"}]
</script>
</body>
</html>`
doc, err := goquery.newdocumentfromreader(strings.newreader(htmlstring))
if err != nil {
panic(err)
}
doc.find("script").each(func(i int, element *goquery.selection) {
_, exists := element.attr("type")
if exists {
file, err := os.create("result.txt")
if err != nil {
panic(err)
}
defer file.close()
stringtowrite := strings.trimspace(element.text())
fmt.println(stringtowrite)
file.writestring(stringtowrite)
}
})
}
生成的文件以及标准输出包含:
[{"class": "companyClass", "location": "companyLocation"}]
请提供您正在处理的 html(或其与问题相关的部分)。
本篇关于《将值输出到控制台而非文件》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
