0
我对Go非常陌生,现在我在解析某些html时稍微努力一下。如何获取HTML元素的内容
的HTML看起来像:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>something</div>
<div id="publication">
<div>I want <span>this</span></div>
</div>
<div>
<div>not this</div>
</div>
</body>
</html>
而且我想这是一个字符串:
<div>I want <span>this</span></div>
我试过html.NewTokenizer()(从golang.org/x/ net/html),但似乎无法从令牌或节点获取元素的全部内容。我也尝试过使用这个深度,但它拿起了其他一些代码。
我也有与goquery这似乎是完美的,代码走:
doc, err := goquery.NewDocument("{url}")
if err != nil {
log.Fatal(err)
}
doc.Find("#publication").Each(func(i int, s *goquery.Selection) {
fmt.Printf("Review %d: %s\n", i, s.Html())
})
但s.Text()将只打印出的文字和s.Html()似乎不存在(?)。
我想解析为XML会的工作,但实际的HTML是非常深的,有将不得不为每个父元素的结构......
任何帮助将是惊人的!
你是什么意思“HTML()”似乎并不存在? https://godoc.org/github.com/PuerkitoBio/goquery#Selection.Html - 它返回2个值,所以你的代码无法编译。 – JimB
啊哈!当然,这看起来更好! - 谢谢@JimB :)现在似乎工作。对于记录,将其更改为: 'html,_:= s.Html()' 'fmt.Printf(“Review%d:%s \ n”,i,html)' –