1 回答
TA贡献1835条经验 获得超7个赞
给定 HTML:
<a href="http://example.com/1">Go to <b>example</b> 1</a>
<p>Some para text</p>
<a href="http://example.com/2">Go to <b>example</b> 2</a>
你只期待文字吗?
Go to example 1
Go to example 2
您期望内部 HTML 吗?
Go to <b>example</b>example 1
Go to <b>example</b>example 2
或者,你期待别的吗?
以下程序仅提供文本或内部 HTML。每次找到锚节点时,它都会保存该节点,然后继续沿着该节点的树向下移动。当它遇到其他节点时,它会检查保存的节点并附加 TextNodes 的文本或将节点的 HTML 呈现到缓冲区。最后,在遍历所有子节点并重新遇到保存的锚节点后,它打印文本字符串和 HTML 缓冲区,重置两个变量,然后将锚节点置零。
我想到了使用缓冲区和 html.Render,并保存特定节点,从Golang 解析 HTML,提取带有标签的所有内容。
以下内容也在Playground中:
package main
import (
"bytes"
"fmt"
"io"
"strings"
"golang.org/x/net/html"
)
func main() {
s := `
<a href="http://example.com/1">Go to <b>example</b> 1</a>
<p>Some para text</p>
<a href="http://example.com/2">Go to <b>example</b> 2</a>
`
doc, _ := html.Parse(strings.NewReader(s))
var nAnchor *html.Node
var sTxt string
var bufInnerHtml bytes.Buffer
w := io.Writer(&bufInnerHtml)
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "a" {
nAnchor = n
}
if nAnchor != nil {
if n != nAnchor { // don't write the a tag and its attributes
html.Render(w, n)
}
if n.Type == html.TextNode {
sTxt += n.Data
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
if n == nAnchor {
fmt.Println("Text:", sTxt)
fmt.Println("InnerHTML:", bufInnerHtml.String())
sTxt = ""
bufInnerHtml.Reset()
nAnchor = nil
}
}
f(doc)
}
Text: Go to example 1
InnerHTML: Go to <b>example</b>example 1
Text: Go to example 2
InnerHTML: Go to <b>example</b>example 2
- 1 回答
- 0 关注
- 105 浏览
添加回答
举报