-
Notifications
You must be signed in to change notification settings - Fork 119
/
htmlparser.go
210 lines (187 loc) · 4.33 KB
/
htmlparser.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*
* Copyright 2019 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package inputs
import (
"bytes"
"fmt"
"strconv"
"strings"
"unicode"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// Table holds a simple table of headers and rows.
type Table struct {
Attributes map[string]string
Headers []string
Rows [][]string
}
// ParseToJSON parses a html fragment or whole document looking for HTML
func ParseToJSON(s []byte) (string, error) {
tables, err := Parse(s)
if err != nil {
return "", err
}
jsonString := "["
closeString := ""
numberOfTables := len(tables)
for i, t := range tables {
if len(t.Rows) == 0 {
continue
}
if i != numberOfTables-1 {
closeString = ","
} else {
closeString = ""
}
tString := convertTable(t, i)
jsonString = jsonString + tString + closeString
}
jsonString = jsonString + "]"
return jsonString, nil
}
func convertTable(t *Table, i int) string {
j := `{"table":[`
header := t.Headers
numberOfRows := len(t.Rows)
for i, row := range t.Rows {
j = j + "{"
numberOfCells := len(row)
for c := range row {
r := ""
if c != numberOfCells-1 {
r = fmt.Sprintf(" \"%s\": \"%s\",", header[c], row[c])
} else {
r = fmt.Sprintf(" \"%s\": \"%s\"", header[c], row[c])
}
j = j + r
}
if i != numberOfRows-1 {
j = j + "},"
} else {
j = j + "}]"
}
}
for k, v := range t.Attributes {
kv := fmt.Sprintf(", \"%s\": \"%s\"", k, v)
j = j + kv
}
j = fmt.Sprintf("%s,\"Index\":%d }", j, i)
return j
}
// Parse parses a html fragment or whole document looking for HTML
// tables. It converts all cells into text, stripping away any HTML content.
func Parse(s []byte) ([]*Table, error) {
node, err := html.Parse(bytes.NewReader(s))
if err != nil {
return nil, err
}
tables := []*Table{}
parse(node, &tables)
for kk, t := range tables {
tables[kk] = addMissingColumns(t)
}
return tables, nil
}
func innerText(n *html.Node) string {
if n.Type == html.TextNode {
stripResult := stripChars(n.Data)
return stripResult
}
result := ""
for x := n.FirstChild; x != nil; x = x.NextSibling {
result += innerText(x)
}
return result
}
func stripChars(input string) string {
var result []string
for _, i := range input {
switch {
// all these considered as space, including tab \t
// '\t', '\n', '\v', '\f', '\r',' ', 0x85, 0xA0
case unicode.IsSpace(i):
result = append(result, " ") // replace tab with space
case unicode.IsPunct(i):
result = append(result, " ") // replace tab with space
default:
result = append(result, string(i))
}
}
return strings.Join(result, "")
}
func containTable(n *html.Node) bool {
if n.DataAtom == atom.Table {
return true
}
result := false
for x := n.FirstChild; x != nil && !result; x = x.NextSibling {
result = containTable(x)
}
return result
}
func parse(n *html.Node, tables *[]*Table) {
strip := strings.TrimSpace
switch n.DataAtom {
case atom.Table:
t := &Table{}
for _, at := range n.Attr {
if t.Attributes == nil {
t.Attributes = map[string]string{}
}
t.Attributes[at.Key] = at.Val
}
*tables = append(*tables, t)
case atom.Th:
t := (*tables)[len(*tables)-1]
t.Headers = append(t.Headers, strip(innerText(n)))
case atom.Tr:
t := (*tables)[len(*tables)-1]
t.Rows = append(t.Rows, []string{})
case atom.Td:
if !containTable(n) {
t := (*tables)[len(*tables)-1]
l := len(t.Rows) - 1
t.Rows[l] = append(t.Rows[l], strip(innerText(n)))
return
}
t := (*tables)[len(*tables)-1]
l := len(t.Rows) - 1
// If the <td> contains <table> element, set the <td> content to "TableElement"
t.Rows[l] = append(t.Rows[l], "TableElement")
}
for child := n.FirstChild; child != nil; child = child.NextSibling {
parse(child, tables)
}
}
func addMissingColumns(t *Table) *Table {
cols := len(t.Headers)
rows := make([][]string, 0, len(t.Rows))
for _, row := range t.Rows {
if len(row) > 0 {
rows = append(rows, row)
}
if len(row) > cols {
cols = len(row)
}
}
for len(t.Headers) < cols {
name := "Col " + strconv.Itoa(len(t.Headers)+1)
t.Headers = append(t.Headers, name)
}
for i, row := range t.Headers {
if len(row) == 0 {
row = "Col " + strconv.Itoa(i)
}
t.Headers[i] = row
}
for kk := range rows {
for len(rows[kk]) < cols {
rows[kk] = append(rows[kk], "")
}
}
t.Rows = rows
return t
}