-
Notifications
You must be signed in to change notification settings - Fork 0
/
colibri.go
266 lines (208 loc) · 6.13 KB
/
colibri.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
// Colibri is an extensible web crawling and scraping framework for Go,
// used to crawl and extract structured data on the web.
package colibri
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
// DefaultResponseBodySize default maximum size of the response body.
DefaultResponseBodySize = 5 * 1024 * 1024
// DefaultDelay default delay time between requests.
DefaultDelay = 5 * time.Second
// DefaultTimeout default timeout used for HTTP requests.
DefaultTimeout = 5 * time.Second
// DefaultUserAgent is the default User-Agent used for requests.
DefaultUserAgent = "colibri/0.3"
)
var (
// ErrClientIsNil returned when Client is nil.
ErrClientIsNil = errors.New("client is nil")
// ErrParserIsNil returned when Parser is nil.
ErrParserIsNil = errors.New("parser is nil")
// ErrResponseBodySize returned when the response body size is too large.
ErrResponseBodySize = errors.New("response body too large")
// ErrRulesIsNil returned when rules are nil.
ErrRulesIsNil = errors.New("rules is nil")
// ErrMaxRedirects are returned when the redirect limit is reached.
ErrMaxRedirects = errors.New("max redirects limit reached")
// ErrRobotstxtRestriction is returned when the page cannot be accessed due to robots.txt restrictions.
ErrRobotstxtRestriction = errors.New("page not accessible due to robots.txt restriction")
)
type (
// Response represents an HTTP response.
Response interface {
// URL returns the URL of the request.
URL() *url.URL
// StatusCode returns the status code.
StatusCode() int
// Header returns the HTTP header of the response.
Header() http.Header
// Body returns the response body.
Body() io.ReadCloser
// Redirects returns the redirected URLs.
Redirects() []*url.URL
// Serializable returns the response value as a map for easy storage or transmission.
Serializable() map[string]any
// Do Colibri Do method wrapper.
// Wraps the Colibri with which the HTTP response was obtained.
Do(rules *Rules) (Response, error)
// Extract Colibri Extract method wrapper.
// Wraps the Colibri with which the HTTP response was obtained.
Extract(rules *Rules) (*Output, error)
}
// Client represents an HTTP client.
Client interface {
// Do makes HTTP requests.
Do(c *Colibri, rules *Rules) (Response, error)
// Clear cleans the fields of the structure.
Clear()
}
// Delay manages the delay between each HTTP request.
Delay interface {
// Wait waits for the previous HTTP request to the same URL and stores
// the timestamp, then starts the calculated delay with the timestamp
// and the specified duration of the delay.
Wait(u *url.URL, duration time.Duration)
// Done warns that an HTTP request has been made to the URL.
Done(u *url.URL)
// Stamp records the time at which the HTTP request to the URL was made.
Stamp(u *url.URL)
// Clear cleans the fields of the structure.
Clear()
}
// RobotsTxt represents a robots.txt parser.
RobotsTxt interface {
// IsAllowed verifies that the User-Agent can access the URL.
IsAllowed(c *Colibri, rules *Rules) error
// Clear cleans the fields of the structure.
Clear()
}
// Parser represents a parser of the response content.
Parser interface {
// Match returns true if the Content-Type is supported by the parser.
Match(contentType string) bool
// Parse parses the response based on the rules.
Parse(rules *Rules, resp Response) (Node, error)
// Clear cleans the fields of the structure.
Clear()
}
)
type Output struct {
// Response to Request.
Response Response
// Data contains the data extracted by the selectors.
Data map[string]any
}
// Serializable returns the value of the output as a map for easy storage or transmission.
func (out *Output) Serializable() map[string]any {
return map[string]any{
"response": out.Response.Serializable(),
"data": out.Data,
}
}
func (out *Output) MarshalJSON() ([]byte, error) {
return json.Marshal(out.Serializable())
}
// Colibri makes HTTP requests and parses the content of the response based on rules.
type Colibri struct {
Client Client
Delay Delay
RobotsTxt RobotsTxt
Parser Parser
}
// New returns a new empty Colibri structure.
func New() *Colibri {
return &Colibri{}
}
// Do makes an HTTP request based on the rules.
func (c *Colibri) Do(rules *Rules) (resp Response, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
if c.Client == nil {
return nil, ErrClientIsNil
}
if rules == nil {
return nil, ErrRulesIsNil
}
if rules.Header == nil {
rules.Header = http.Header{}
}
if rules.Header.Get("User-Agent") == "" {
rules.Header.Set("User-Agent", DefaultUserAgent)
}
// ResponseBodySize
if rules.ResponseBodySize == 0 {
rules.ResponseBodySize = DefaultResponseBodySize
}
// Delay
if rules.Delay == 0 {
rules.Delay = DefaultDelay
}
// Timeout
if rules.Timeout <= 0 {
rules.Timeout = DefaultTimeout
}
if (c.RobotsTxt != nil) && !rules.IgnoreRobotsTxt {
err := c.RobotsTxt.IsAllowed(c, rules)
if err != nil {
return nil, err
}
}
if (c.Delay != nil) && (rules.Delay > 0) {
c.Delay.Wait(rules.URL, rules.Delay)
defer c.Delay.Done(rules.URL)
}
resp, err = c.Client.Do(c, rules)
if (c.Delay != nil) && (resp != nil) {
c.Delay.Stamp(resp.URL())
}
return resp, err
}
// Extract makes the HTTP request and parses the content of the response based on the rules.
func (c *Colibri) Extract(rules *Rules) (output *Output, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
if c.Parser == nil {
return nil, ErrParserIsNil
}
output = &Output{}
output.Response, err = c.Do(rules)
if err != nil {
return nil, err
}
if len(rules.Selectors) > 0 {
var parent Node
parent, err = c.Parser.Parse(rules, output.Response)
if err == nil {
output.Data, err = FindSelectors(rules, output.Response, parent)
}
}
return output, err
}
// Clear cleans the fields of the structure.
func (c *Colibri) Clear() {
if c.Client != nil {
c.Client.Clear()
}
if c.Delay != nil {
c.Delay.Clear()
}
if c.RobotsTxt != nil {
c.RobotsTxt.Clear()
}
if c.Parser != nil {
c.Parser.Clear()
}
}