-
Notifications
You must be signed in to change notification settings - Fork 3
/
html2data.go
338 lines (281 loc) · 8.52 KB
/
html2data.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
Package html2data - extract data from HTML via CSS selectors
Install package and command line utility:
go install github.com/msoap/html2data/cmd/html2data@latest
Install package only:
go get -u github.com/msoap/html2data
Allowed pseudo-selectors:
:attr(attr_name) - for getting attributes instead text
:html - for getting HTML instead text
:get(N) - get n-th element from list
Command line utility:
html2data URL "css selector"
html2data file.html "css selector"
cat file.html | html2data "css selector"
*/
package html2data
import (
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html/charset"
)
// docOrSelection - for exec .Find
type docOrSelection interface {
Find(string) *goquery.Selection
}
// Doc - html document for parse
type Doc struct {
doc docOrSelection
Err error
}
// CSSSelector - selector with settings
type CSSSelector struct {
selector string
attrName string
getHTML bool
getNth int
}
// Cfg - config for GetData* methods
type Cfg struct {
DontTrimSpaces bool // get text as is, by default trim spaces
}
// getDataFromDocOrSelection - extract data by CSS-selectors from goquery.Selection or goquery.Doc
func (doc Doc) getDataFromDocOrSelection(docOrSelection docOrSelection, selectors map[string]string, config Cfg) (result map[string][]string, err error) {
if doc.Err != nil {
return result, fmt.Errorf("parse document error: %s", doc.Err)
}
defer func() {
if errRecoverRaw := recover(); errRecoverRaw != nil {
result, err = map[string][]string{}, fmt.Errorf("%s", errRecoverRaw)
}
}()
result = map[string][]string{}
for name, selectorRaw := range selectors {
selector := parseSelector(selectorRaw)
texts := []string{}
docOrSelection.Find(selector.selector).Each(func(i int, selection *goquery.Selection) {
if selector.getNth > 0 && selector.getNth != i+1 {
return
}
var foundText string
switch {
case selector.attrName != "":
foundText = selection.AttrOr(selector.attrName, "")
case selector.getHTML:
foundText, err = selection.Html()
if err != nil {
return
}
default:
foundText = selection.Text()
}
if !config.DontTrimSpaces {
foundText = strings.TrimSpace(foundText)
}
texts = append(texts, foundText)
})
result[name] = texts
}
return result, err
}
var htmlAttrRe = regexp.MustCompile(`^\s*(\w+)\s*(?:\(\s*(\w+)\s*\))?\s*$`)
// parseSelector - parse pseudo-selectors:
// :attr(href) - for getting attribute instead text node
func parseSelector(inputSelector string) (outSelector CSSSelector) {
parts := strings.Split(inputSelector, ":")
outSelector.selector, parts = parts[0], parts[1:]
for _, part := range parts {
reParts := htmlAttrRe.FindStringSubmatch(part)
switch {
case len(reParts) == 3 && reParts[1] == "attr":
outSelector.attrName = reParts[2]
case len(reParts) == 3 && reParts[1] == "html":
outSelector.getHTML = true
case len(reParts) == 3 && reParts[1] == "get":
outSelector.getNth, _ = strconv.Atoi(reParts[2]) // #nosec
default:
outSelector.selector += ":" + part
}
}
return outSelector
}
// getConfig - get first config element from list
func getConfig(configs []Cfg) Cfg {
switch {
case len(configs) == 0:
return Cfg{}
case len(configs) == 1:
return configs[0]
default:
panic("[]Cfg length must be equal 0 or 1")
}
}
// GetData - extract data by CSS-selectors
//
// texts, err := doc.GetData(map[string]string{"h1": "h1"})
func (doc Doc) GetData(selectors map[string]string, configs ...Cfg) (result map[string][]string, err error) {
result, err = doc.getDataFromDocOrSelection(doc.doc, selectors, getConfig(configs))
return result, err
}
// GetDataFirst - extract data by CSS-selectors, get first entry for each selector or ""
//
// texts, err := doc.GetDataFirst(map[string]string{"h1": "h1"})
func (doc Doc) GetDataFirst(selectors map[string]string, configs ...Cfg) (result map[string]string, err error) {
resultRaw, err := doc.getDataFromDocOrSelection(doc.doc, selectors, getConfig(configs))
if err != nil {
return result, err
}
result = map[string]string{}
for key := range resultRaw {
if len(resultRaw[key]) > 0 {
result[key] = resultRaw[key][0]
} else {
result[key] = ""
}
}
return result, err
}
// GetDataNested - extract nested data by CSS-selectors from another CSS-selector
//
// texts, err := doc.GetDataNested("CSS.selector", map[string]string{"h1": "h1"}) - get h1 from CSS.selector
func (doc Doc) GetDataNested(selectorRaw string, nestedSelectors map[string]string, configs ...Cfg) (result []map[string][]string, err error) {
if doc.Err != nil {
return result, fmt.Errorf("parse document error: %s", doc.Err)
}
selector := parseSelector(selectorRaw)
defer func() {
if errRecoverRaw := recover(); errRecoverRaw != nil {
result, err = []map[string][]string{}, fmt.Errorf("%s", errRecoverRaw)
}
}()
result = []map[string][]string{}
doc.doc.Find(selector.selector).Each(func(i int, selection *goquery.Selection) {
if selector.getNth > 0 && selector.getNth != i+1 {
return
}
nestedResult, nestedErr := doc.getDataFromDocOrSelection(selection, nestedSelectors, getConfig(configs))
if nestedErr != nil {
err = nestedErr
return
}
result = append(result, nestedResult)
})
return result, err
}
// GetDataNestedFirst - extract nested data by CSS-selectors from another CSS-selector
// get first entry for each selector or ""
//
// texts, err := doc.GetDataNestedFirst("CSS.selector", map[string]string{"h1": "h1"}) - get h1 from CSS.selector
func (doc Doc) GetDataNestedFirst(selectorRaw string, nestedSelectors map[string]string, configs ...Cfg) (result []map[string]string, err error) {
resultRaw, err := doc.GetDataNested(selectorRaw, nestedSelectors, configs...)
if err != nil {
return result, err
}
result = []map[string]string{}
for i, resultRawPart := range resultRaw {
result = append(result, map[string]string{})
for key := range resultRawPart {
if len(resultRawPart[key]) > 0 {
result[i][key] = resultRawPart[key][0]
} else {
result[i][key] = ""
}
}
}
return result, err
}
// GetDataSingle - extract data by one CSS-selector
//
// title, err := doc.GetDataSingle("title")
func (doc Doc) GetDataSingle(selector string, configs ...Cfg) (result string, err error) {
texts, err := doc.GetData(map[string]string{"single": selector}, getConfig(configs))
if err != nil {
return result, err
}
if textOne, ok := texts["single"]; ok && len(textOne) > 0 {
result = textOne[0]
}
return result, err
}
// FromReader - get doc from io.Reader
func FromReader(reader io.Reader) Doc {
doc, err := goquery.NewDocumentFromReader(reader)
return Doc{doc, err}
}
// FromFile - get doc from file
func FromFile(fileName string) Doc {
fileReader, err := os.Open(fileName) // #nosec
if err != nil {
return Doc{Err: err}
}
doc := FromReader(fileReader)
err = fileReader.Close()
if err != nil {
return Doc{Err: err}
}
return doc
}
// URLCfg - config for FromURL()
type URLCfg struct {
UA string // custom user-agent
TimeOut int // timeout in seconds
DontDetectCharset bool // don't autoconvert to UTF8
}
// FromURL - get doc from URL
//
// FromURL("https://url")
// FromURL("https://url", URLCfg{UA: "Custom UA 1.0", TimeOut: 10})
func FromURL(URL string, config ...URLCfg) Doc {
ua, timeout, dontDetectCharset := "", 0, false
if len(config) == 1 {
ua = config[0].UA
timeout = config[0].TimeOut
dontDetectCharset = config[0].DontDetectCharset
} else if len(config) > 1 {
panic("FromURL(): only one config argument allowed")
}
htmlReader, err := getHTMLPage(URL, ua, timeout, dontDetectCharset)
if err != nil {
return Doc{Err: err}
}
return FromReader(htmlReader)
}
// getHTMLPage - get html by http(s) as http.Response
func getHTMLPage(url string, ua string, timeout int, dontDetectCharset bool) (htmlReader io.Reader, err error) {
cookie, err := cookiejar.New(nil)
if err != nil {
return htmlReader, err
}
client := &http.Client{
Jar: cookie,
Timeout: time.Duration(timeout) * time.Second,
}
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return htmlReader, err
}
if ua != "" {
request.Header.Set("User-Agent", ua)
}
response, err := client.Do(request)
if err != nil {
return htmlReader, err
}
if contentType := response.Header.Get("Content-Type"); contentType != "" && !dontDetectCharset {
htmlReader, err = charset.NewReader(response.Body, contentType)
if err != nil {
return htmlReader, err
}
} else {
return response.Body, nil
}
return htmlReader, nil
}