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
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package flyscrape
import (
"log"
"regexp"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/cornelk/hashmap"
"github.com/nlnwa/whatwg-url/url"
)
type ScrapeParams struct {
HTML string
URL string
}
type ScrapeOptions struct {
URL string `json:"url"`
AllowedDomains []string `json:"allowedDomains"`
BlockedDomains []string `json:"blockedDomains"`
AllowedURLs []string `json:"allowedURLs"`
BlockedURLs []string `json:"blockedURLs"`
Proxy string `json:"proxy"`
Depth int `json:"depth"`
Rate float64 `json:"rate"`
}
type ScrapeResult struct {
URL string `json:"url"`
Data any `json:"data,omitempty"`
Links []string `json:"-"`
Error error `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
func (s *ScrapeResult) omit() bool {
return s.Error == nil && s.Data == nil
}
type ScrapeFunc func(ScrapeParams) (any, error)
type FetchFunc func(url string) (string, error)
type target struct {
url string
depth int
}
type Scraper struct {
ScrapeOptions ScrapeOptions
ScrapeFunc ScrapeFunc
FetchFunc FetchFunc
visited *hashmap.Map[string, struct{}]
wg *sync.WaitGroup
jobs chan target
results chan ScrapeResult
allowedURLsRE []*regexp.Regexp
blockedURLsRE []*regexp.Regexp
}
func (s *Scraper) init() {
s.visited = hashmap.New[string, struct{}]()
s.wg = &sync.WaitGroup{}
s.jobs = make(chan target, 1024)
s.results = make(chan ScrapeResult)
if s.FetchFunc == nil {
s.FetchFunc = Fetch()
}
if s.ScrapeOptions.Proxy != "" {
s.FetchFunc = ProxiedFetch(s.ScrapeOptions.Proxy)
}
if s.ScrapeOptions.Rate == 0 {
s.ScrapeOptions.Rate = 100
}
if u, err := url.Parse(s.ScrapeOptions.URL); err == nil {
s.ScrapeOptions.AllowedDomains = append(s.ScrapeOptions.AllowedDomains, u.Host())
}
for _, pat := range s.ScrapeOptions.AllowedURLs {
re, err := regexp.Compile(pat)
if err != nil {
continue
}
s.allowedURLsRE = append(s.allowedURLsRE, re)
}
for _, pat := range s.ScrapeOptions.BlockedURLs {
re, err := regexp.Compile(pat)
if err != nil {
continue
}
s.blockedURLsRE = append(s.blockedURLsRE, re)
}
}
func (s *Scraper) Scrape() <-chan ScrapeResult {
s.init()
s.enqueueJob(s.ScrapeOptions.URL, s.ScrapeOptions.Depth)
go s.worker()
go s.waitClose()
return s.results
}
func (s *Scraper) worker() {
var (
rate = time.Duration(float64(time.Second) / s.ScrapeOptions.Rate)
leakyjobs = leakychan(s.jobs, rate)
)
for job := range leakyjobs {
go func(job target) {
defer s.wg.Done()
res := s.process(job)
if !res.omit() {
s.results <- res
}
if job.depth <= 0 {
return
}
for _, l := range res.Links {
if _, ok := s.visited.Get(l); ok {
continue
}
allowed := s.isDomainAllowed(l) && s.isURLAllowed(l)
if !allowed {
continue
}
s.enqueueJob(l, job.depth-1)
}
}(job)
}
}
func (s *Scraper) process(job target) (res ScrapeResult) {
res.URL = job.url
res.Timestamp = time.Now()
html, err := s.FetchFunc(job.url)
if err != nil {
res.Error = err
return
}
res.Links = links(html, job.url)
res.Data, err = s.ScrapeFunc(ScrapeParams{HTML: html, URL: job.url})
if err != nil {
res.Error = err
return
}
return
}
func (s *Scraper) enqueueJob(url string, depth int) {
s.wg.Add(1)
select {
case s.jobs <- target{url: url, depth: depth}:
s.visited.Set(url, struct{}{})
default:
log.Println("queue is full, can't add url:", url)
s.wg.Done()
}
}
func (s *Scraper) isDomainAllowed(rawurl string) bool {
u, err := url.Parse(rawurl)
if err != nil {
return false
}
host := u.Host()
ok := false
for _, domain := range s.ScrapeOptions.AllowedDomains {
if domain == "*" || host == domain {
ok = true
break
}
}
for _, domain := range s.ScrapeOptions.BlockedDomains {
if host == domain {
ok = false
break
}
}
return ok
}
func (s *Scraper) isURLAllowed(rawurl string) bool {
// allow root url
if rawurl == s.ScrapeOptions.URL {
return true
}
// allow if no filter is set
if len(s.allowedURLsRE) == 0 && len(s.blockedURLsRE) == 0 {
return true
}
ok := false
if len(s.allowedURLsRE) == 0 {
ok = true
}
for _, re := range s.allowedURLsRE {
if re.MatchString(rawurl) {
ok = true
break
}
}
for _, re := range s.blockedURLsRE {
if re.MatchString(rawurl) {
ok = false
break
}
}
return ok
}
func (s *Scraper) waitClose() {
s.wg.Wait()
close(s.jobs)
close(s.results)
}
func links(html string, origin string) []string {
var links []string
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
return nil
}
urlParser := url.NewParser(url.WithPercentEncodeSinglePercentSign())
uniqueLinks := make(map[string]bool)
doc.Find("a").Each(func(i int, s *goquery.Selection) {
link, _ := s.Attr("href")
parsedLink, err := urlParser.ParseRef(origin, link)
if err != nil || !isValidLink(parsedLink) {
return
}
absLink := parsedLink.Href(true)
if !uniqueLinks[absLink] {
links = append(links, absLink)
uniqueLinks[absLink] = true
}
})
return links
}
func isValidLink(link *url.Url) bool {
if link.Scheme() != "" && link.Scheme() != "http" && link.Scheme() != "https" {
return false
}
if strings.HasPrefix(link.String(), "javascript:") {
return false
}
return true
}
func leakychan[T any](in chan T, rate time.Duration) chan T {
ticker := time.NewTicker(rate)
sem := make(chan struct{}, 1)
c := make(chan T)
go func() {
for range ticker.C {
sem <- struct{}{}
}
}()
go func() {
for v := range in {
<-sem
c <- v
}
ticker.Stop()
close(c)
}()
return c
}
|