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个赞
尝试这样的方法来制作二维数组并处理可变行大小:
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 关注
- 248 浏览
添加回答
举报
