-
Notifications
You must be signed in to change notification settings - Fork 55
/
crawler.js
347 lines (302 loc) · 10.4 KB
/
crawler.js
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
339
340
341
342
343
344
345
346
347
var request = require('request');
var _ = require('underscore');
var url = require('url');
var DEFAULT_DEPTH = 2;
var DEFAULT_MAX_CONCURRENT_REQUESTS = 10;
var DEFAULT_MAX_REQUESTS_PER_SECOND = 100;
var DEFAULT_USERAGENT = 'crawler/js-crawler';
/*
* Executor that handles throttling and task processing rate.
*/
function Executor(opts) {
this.maxRatePerSecond = opts.maxRatePerSecond;
this.onFinished = opts.finished || function() {};
this.canProceed = opts.canProceed || function() {return true;};
this.queue = [];
this.isStopped = false;
this.timeoutMs = (1 / this.maxRatePerSecond) * 1000;
}
Executor.prototype.submit = function(func, context, args, shouldSkip) {
this.queue.push({
func: func,
context: context,
args: args,
shouldSkip: shouldSkip
});
};
Executor.prototype.start = function() {
this._processQueueItem();
};
Executor.prototype.stop = function() {
this.isStopped = true;
};
Executor.prototype._processQueueItem = function() {
var self = this;
if (this.canProceed()) {
if (this.queue.length !== 0) {
var nextExecution = this.queue.shift();
var shouldSkipNext = (nextExecution.shouldSkip && nextExecution.shouldSkip.call(nextExecution.context));
if (shouldSkipNext) {
setTimeout(function() {
self._processQueueItem();
});
return;
} else {
nextExecution.func.apply(nextExecution.context, nextExecution.args);
}
}
}
if (this.isStopped) {
return;
}
setTimeout(function() {
self._processQueueItem();
}, this.timeoutMs);
};
/*
* Main crawler functionality.
*/
function Crawler() {
/*
* Urls that the Crawler has visited, as some pages may be in the middle of a redirect chain, not all the knownUrls will be actually
* reported in the onSuccess or onFailure callbacks, only the final urls in the corresponding redirect chains
*/
this.knownUrls = {};
/*
* Urls that were reported in the onSuccess or onFailure callbacks. this.crawledUrls is a subset of this.knownUrls, and matches it
* iff there were no redirects while crawling.
*/
this.crawledUrls = [];
this.depth = DEFAULT_DEPTH;
this.ignoreRelative = false;
this.userAgent = DEFAULT_USERAGENT;
this.maxConcurrentRequests = DEFAULT_MAX_CONCURRENT_REQUESTS;
this.maxRequestsPerSecond = DEFAULT_MAX_REQUESTS_PER_SECOND;
this.shouldCrawl = function(url) {
return true;
};
this.shouldCrawlLinksFrom = function(url) {
return true;
};
//Urls that are queued for crawling, for some of them HTTP requests may not yet have been issued
this._currentUrlsToCrawl = [];
this._concurrentRequestNumber = 0;
//Injecting request as a dependency for unit test support
this.request = request;
}
Crawler.prototype.configure = function(options) {
this.depth = (options && options.depth) || this.depth;
this.depth = Math.max(this.depth, 0);
this.ignoreRelative = (options && options.ignoreRelative) || this.ignoreRelative;
this.userAgent = (options && options.userAgent) || this.userAgent;
this.maxConcurrentRequests = (options && options.maxConcurrentRequests) || this.maxConcurrentRequests;
this.maxRequestsPerSecond = (options && options.maxRequestsPerSecond) || this.maxRequestsPerSecond;
this.shouldCrawl = (options && options.shouldCrawl) || this.shouldCrawl;
this.shouldCrawlLinksFrom = (options && options.shouldCrawlLinksFrom) || this.shouldCrawlLinksFrom;
this.onSuccess = _.noop;
this.onFailure = _.noop;
this.onAllFinished = _.noop;
return this;
};
Crawler.prototype._createExecutor = function() {
var self = this;
return new Executor({
maxRatePerSecond: this.maxRequestsPerSecond,
canProceed: function() {
return self._concurrentRequestNumber < self.maxConcurrentRequests;
}
});
};
Crawler.prototype.crawl = function(url, onSuccess, onFailure, onAllFinished) {
this.workExecutor = this._createExecutor();
this.workExecutor.start();
if (typeof url !== 'string') {
var options = url;
onSuccess = options.success;
onFailure = options.failure;
onAllFinished = options.finished;
url = options.url;
}
this.onSuccess = onSuccess;
this.onFailure = onFailure;
this.onAllFinished = onAllFinished;
this._crawlUrl(url, null, this.depth);
return this;
};
/*
* TODO: forgetCrawled, _startedCrawling, _finishedCrawling, _requestUrl belong together?
* Group them together?
*/
Crawler.prototype.forgetCrawled = function() {
this.knownUrls = {};
this.crawledUrls = [];
return this;
};
Crawler.prototype._startedCrawling = function(url) {
if (this._currentUrlsToCrawl.indexOf(url) < 0) {
this._currentUrlsToCrawl.push(url);
}
};
Crawler.prototype._finishedCrawling = function(url) {
var indexOfUrl = this._currentUrlsToCrawl.indexOf(url);
this._currentUrlsToCrawl.splice(indexOfUrl, 1);
if (this._currentUrlsToCrawl.length === 0) {
this.onAllFinished && this.onAllFinished(this.crawledUrls);
this.workExecutor && this.workExecutor.stop();
}
}
Crawler.prototype._requestUrl = function(options, callback) {
//console.log('_requestUrl: options = ', options);
var self = this;
var url = options.url;
//Do not request a url if it has already been crawled
if (_.contains(self._currentUrlsToCrawl, url) || _.contains(self.knownUrls, url)) {
return;
}
self._startedCrawling(url);
this.workExecutor.submit(function(options, callback) {
self._concurrentRequestNumber++;
self.request(options, function(error, response, body) {
self._redirects = this._redirect.redirects;
callback(error, response, body);
self._finishedCrawling(url);
self._concurrentRequestNumber--;
});
}, null, [options, callback], function shouldSkip() {
//console.log('Should skip? url = ', url, _.contains(self.knownUrls, url) || !self.shouldCrawl(url));
var shouldCrawlUrl = self.shouldCrawl(url);
if (!shouldCrawlUrl) {
self._finishedCrawling(url);
}
return _.contains(self.knownUrls, url) || !shouldCrawlUrl;
});
};
Crawler.prototype._crawlUrl = function(url, referer, depth) {
//console.log('_crawlUrl: url = %s, depth = %s', url, depth);
if ((depth === 0) || this.knownUrls[url]) {
return;
}
var self = this;
this._requestUrl({
url: url,
encoding: null, // Added by @tibetty so as to avoid request treating body as a string by default
rejectUnauthorized : false,
followRedirect: true,
followAllRedirects: true,
headers: {
'User-Agent': this.userAgent,
'Referer': referer
}
}, function(error, response) {
if (self.knownUrls[url]) {
//Was already crawled while the request has been processed, no need to call callbacks
return;
}
self.knownUrls[url] = true;
_.each(self._redirects, function(redirect) {
self.knownUrls[redirect.redirectUri] = true;
});
//console.log('analyzing url = ', url);
var isTextContent = self._isTextContent(response);
var body = isTextContent ? self._getDecodedBody(response) : '<<...binary content (omitted by js-crawler)...>>';
if (!error && (response.statusCode === 200)) {
//If no redirects, then response.request.uri.href === url, otherwise last url
var lastUrlInRedirectChain = response.request.uri.href;
//console.log('lastUrlInRedirectChain = %s', lastUrlInRedirectChain);
if (self.shouldCrawl(lastUrlInRedirectChain)) {
self.onSuccess({
url: lastUrlInRedirectChain,
status: response.statusCode,
content: body,
error: error,
response: response,
body: body,
referer: referer || ""
});
self.knownUrls[lastUrlInRedirectChain] = true;
self.crawledUrls.push(lastUrlInRedirectChain);
if (self.shouldCrawlLinksFrom(lastUrlInRedirectChain) && depth > 1 && isTextContent) {
self._crawlUrls(self._getAllUrls(lastUrlInRedirectChain, body), lastUrlInRedirectChain, depth - 1);
}
}
} else if (self.onFailure) {
self.onFailure({
url: url,
status: response ? response.statusCode : undefined,
content: body,
error: error,
response: response,
body: body,
referer: referer || ""
});
self.crawledUrls.push(url);
}
});
};
Crawler.prototype._isTextContent = function(response) {
return Boolean(response && response.headers && response.headers['content-type']
&& response.headers['content-type'].match(/^text\/html.*$/));
};
Crawler.prototype._getDecodedBody = function(response) {
var defaultEncoding = 'utf8';
var encoding = defaultEncoding;
if (response.headers['content-encoding']) {
encoding = response.headers['content-encoding'];
}
//console.log('encoding = "' + encoding + '"');
var decodedBody;
try {
decodedBody = response.body.toString(encoding);
} catch (decodingError) {
decodedBody = response.body.toString(defaultEncoding);
}
return decodedBody;
};
Crawler.prototype._stripComments = function(str) {
return str.replace(/<!--.*?-->/g, '');
};
Crawler.prototype._getBaseUrl = function(defaultBaseUrl, body) {
/*
* Resolving the base url following
* the algorithm from https://www.w3.org/TR/html5/document-metadata.html#the-base-element
*/
var baseUrlRegex = /<base href="(.*?)">/;
var baseUrlInPage = body.match(baseUrlRegex);
if (!baseUrlInPage) {
return defaultBaseUrl;
}
return url.resolve(defaultBaseUrl, baseUrlInPage[1]);
};
Crawler.prototype._isLinkProtocolSupported = function(link) {
return (link.indexOf('://') < 0 && link.indexOf('mailto:') < 0)
|| link.indexOf('http://') >= 0 || link.indexOf('https://') >= 0;
};
Crawler.prototype._getAllUrls = function(defaultBaseUrl, body) {
var self = this;
body = this._stripComments(body);
var baseUrl = this._getBaseUrl(defaultBaseUrl, body);
var linksRegex = self.ignoreRelative ? /<a[^>]+?href=["'].*?:\/\/.*?["']/gmi : /<a[^>]+?href=["'].*?["']/gmi;
var links = body.match(linksRegex) || [];
//console.log('body = ', body);
var urls = _.chain(links)
.map(function(link) {
var match = /href=[\"\'](.*?)[#\"\']/i.exec(link);
link = match[1];
link = url.resolve(baseUrl, link);
return link;
})
.uniq()
.filter(function(link) {
return self._isLinkProtocolSupported(link) && self.shouldCrawl(link);
})
.value();
//console.log('urls to crawl = ', urls);
return urls;
};
Crawler.prototype._crawlUrls = function(urls, referer, depth) {
var self = this;
_.each(urls, function(url) {
self._crawlUrl(url, referer, depth);
});
};
module.exports = Crawler;