forked from MarkSchmitt/tc4400_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
96 lines (87 loc) · 2.17 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"bytes"
"io"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func parseTables(r io.ReadCloser) (tables [][][]string, err error) {
doc, err := html.Parse(r)
if err != nil {
return nil, err
}
tables = [][][]string{}
n := doc
for {
if n.Type == html.ElementNode && n.DataAtom == atom.Table {
tables = append(tables, parseTable(n))
} else if n.FirstChild != nil {
n = n.FirstChild
continue
}
if n.NextSibling != nil {
n = n.NextSibling
} else if n.Parent != doc && n.Parent.NextSibling != nil {
n = n.Parent.NextSibling
} else {
break
}
}
return tables, nil
}
func parseTable(tableNode *html.Node) (table [][]string) {
table = [][]string{}
var contentBuffer bytes.Buffer
bodyNode := tableNode.FirstChild
for {
if bodyNode == nil {
break
}
if bodyNode.Type == html.ElementNode && (bodyNode.DataAtom == atom.Thead || bodyNode.DataAtom == atom.Tbody) {
rowNode := bodyNode.FirstChild
for {
if rowNode == nil {
break
}
if rowNode.Type == html.ElementNode && rowNode.DataAtom == atom.Tr {
row := []string{}
cellNode := rowNode.FirstChild
for {
if cellNode == nil {
break
}
if cellNode.Type == html.ElementNode && (cellNode.DataAtom == atom.Th || cellNode.DataAtom == atom.Td) {
contentBuffer.Reset()
contentNode := cellNode.FirstChild
for {
if contentNode == nil {
break
}
if contentNode.Type == html.TextNode {
contentBuffer.WriteString(contentNode.Data)
} else if contentNode.FirstChild != nil {
contentNode = contentNode.FirstChild
continue
}
if contentNode.NextSibling != nil {
contentNode = contentNode.NextSibling
} else if contentNode.Parent != cellNode {
contentNode = contentNode.Parent.NextSibling
} else {
contentNode = nil
}
}
row = append(row, strings.TrimSpace(contentBuffer.String()))
}
cellNode = cellNode.NextSibling
}
table = append(table, row)
}
rowNode = rowNode.NextSibling
}
}
bodyNode = bodyNode.NextSibling
}
return table
}