我需要抓取一个网站,我感兴趣的标签是:
<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语句并没有打印任何东西到文件中。该文件仍为空。
我的查询似乎是错误的,它输出了两个元素;第一个元素的长度为零,这是打印到文件中的元素,第二个元素的内容是实际内容,它打印到stdout,但没有打印到文件中。
您能建议对我的代码进行更正,以便将内容正确打印到文件中吗?我猜我的goquery查询可能有错误。
发布于 2021-10-10 18:59:14
快速测试表明,只需调用.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)
}
})
}
生成的文件以及stdout包含:
[{"class": "companyClass", "location": "companyLocation"}]
请提供您正在使用的html (或与问题相关的部分)。
https://stackoverflow.com/questions/69513943
复制相似问题