我有html文件
<value>1,2,3</value>
<value>,1,3,5</value>
以及使用下面的代码提取文本的内容,但它只打印“值”标签(css 选择器)。如何打印标签之间的文本而不是使用 golang html 包?
z := html.NewTokenizer(b)
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
return
case tt == html.StartTagToken:
t := z.Token()
isAnchor := t.Data == "value"
if isAnchor {
fmt.Println(t.Data)
}
}
}
最佳答案
这似乎对我有用:
r := strings.NewReader("<value>1,2,3</value><value>,1,3,5</value>")
doc, err := html.Parse(r)
if err != nil {
log.Fatal(err)
}
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "value" {
fmt.Println(n.FirstChild.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
我认为关键是在找到“值”节点后抓取 FirstChild。
关于html - 如何使用 html 包在 golang 中的 css 选择器之间打印文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40743101/