2 回答

TA貢獻2065條經驗 獲得超14個贊
您可以golang.org/x/net/html只使用包裹。
var body = strings.NewReader(`
<html>
<body>
<table>
<tr>
<td>Row 1, Content 1</td>
<td>Row 1, Content 2</td>
<td>Row 1, Content 3</td>
<td>Row 1, Content 4</td>
</tr>
<tr>
<td>Row 2, Content 1</td>
<td>Row 2, Content 2</td>
<td>Row 2, Content 3</td>
<td>Row 2, Content 4</td>
</tr>
</table>
</body>
</html>`)
func main() {
z := html.NewTokenizer(body)
content := []string{}
// While have not hit the </html> tag
for z.Token().Data != "html" {
tt := z.Next()
if tt == html.StartTagToken {
t := z.Token()
if t.Data == "td" {
inner := z.Next()
if inner == html.TextToken {
text := (string)(z.Text())
t := strings.TrimSpace(text)
content = append(content, t)
}
}
}
}
// Print to check the slice's content
fmt.Println(content)
}
此代碼僅針對這種典型的 HTML 模式編寫,但將其重構為更通用并不難。

TA貢獻1803條經驗 獲得超3個贊
嘗試這樣的方法來制作二維數組并處理可變行大?。?/p>
z := html.NewTokenizer(body)
table := [][]string{}
row := []string{}
for z.Token().Data != "html" {
tt := z.Next()
if tt == html.StartTagToken {
t := z.Token()
if t.Data == "tr" {
if len(row) > 0 {
table = append(table, row)
row = []string{}
}
}
if t.Data == "td" {
inner := z.Next()
if inner == html.TextToken {
text := (string)(z.Text())
t := strings.TrimSpace(text)
row = append(row, t)
}
}
}
}
if len(row) > 0 {
table = append(table, row)
}
- 2 回答
- 0 關注
- 216 瀏覽
添加回答
舉報