-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
62 lines (50 loc) · 1.18 KB
/
parser.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
package main
import (
"regexp"
"strings"
"github.com/PuerkitoBio/goquery"
)
/*
* DOM parser
* Parses HTML downloaded by the worker and returns elements
* specified in a json config.
*
* Regex match string when provided in a "parent" overrides
* the regex string provided in the children elements
*/
func parse(conf []JobConfigField, DOM string, parentRegex string) map[string]interface{} {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(DOM))
if err != nil {
return nil
}
var fields = make(map[string]interface{}, len(conf))
for _, field := range conf {
if field.Attr != "" {
attr, ok := doc.Find(field.Selector).Attr(field.Attr)
if ok {
fields[field.Name] = attr
}
} else {
fields[field.Name] = doc.Find(field.Selector).Text()
}
if field.Children != nil {
fields[field.Name] = parse(field.Children, DOM, field.Regex)
continue
}
if parentRegex != "" {
field.Regex = parentRegex
}
if field.Regex != "" {
c, err := regexp.Compile(field.Regex)
if err != nil {
// Log error
}
f := c.FindString(fields[field.Name].(string))
if f == "" {
// Log error
}
fields[field.Name] = f
}
}
return fields
}