-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrago.go
94 lines (71 loc) · 1.55 KB
/
scrago.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
package scrago
import (
"os"
"encoding/json"
"net/url"
"github.com/PuerkitoBio/goquery"
)
type Record map[string]interface{}
type ParseFunc func(*goquery.Document, chan<- Record)
type Spider struct {
Name string
StartURLs []string
Parse ParseFunc
}
func get_doc(doc *goquery.Document, err error) *goquery.Document {
if err != nil {
panic(err)
}
return doc
}
func get_doc_from_filename(urlString string) *goquery.Document {
u, err := url.Parse(urlString)
if err != nil {
panic(err)
}
f, err := os.OpenFile(u.Path, os.O_RDONLY, 0444)
if err != nil {
panic(err)
}
defer f.Close()
return get_doc(goquery.NewDocumentFromReader(f))
}
func get_doc_from_url(urlString string) *goquery.Document {
return get_doc(goquery.NewDocument(urlString))
}
func run_scrape(urlString string, c chan<- Record, parser ParseFunc) {
u, err := url.Parse(urlString)
if err != nil {
panic(err)
}
var doc_getter func(string) *goquery.Document
if u.Scheme == "file" {
doc_getter = get_doc_from_filename
} else {
doc_getter = get_doc_from_url
}
parser(doc_getter(urlString), c)
}
func RunSpider(spider Spider) {
records := make([]Record, 0)
c := make(chan Record)
go func() {
for rec := range c {
records = append(records, rec)
}
}()
func() {
defer close(c)
for _, u := range spider.StartURLs {
run_scrape(u, c, spider.Parse)
}
}()
enc := json.NewEncoder(os.Stdout)
if err := enc.Encode(records); err != nil {
panic(err)
}
}
func Attr(sel *goquery.Selection, name string) string {
res, _ := sel.Attr(name)
return res
}