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 關注
- 130 瀏覽
添加回答
舉報