node-crawler
Most powerful crawling/scraping package for Node, happy hacking :)
Features:
- server-side DOM & automatic jQuery insertion with Cheerio (default) or JSDOM
- Configurable pool size and retries
- Control rate limit
- Priority queue of requests
- forceUTF8 mode to let crawler deal for you with charset detection and conversion
Here is the CHANGELOG
How to install
$ npm install crawler
Crash course
var Crawler = require("crawler");
var url = require('url');
var c = new Crawler({
maxConnections : 10,
callback : function (error, res, done) {
if(error){
console.log(error);
}else{
var $ = res.$;
console.log($("title").text());
}
done();
}
});
c.queue('http://www.amazon.com');
c.queue(['http://www.google.com/','http://www.yahoo.com']);
c.queue([{
uri: 'http://parishackers.org/',
jQuery: false,
callback: function (error, res, done) {
if(error){
console.log(error);
}else{
console.log('Grabbed', res.body.length, 'bytes');
}
done();
}
}]);
c.queue([{
html: '<p>This is a <strong>test</strong></p>'
}]);
Work with bottleneck
Control rate limit for with limiter. All tasks submit to a limiter will abide the rateLimit
and maxConnections
restrictions of the limiter. rateLimit
is the minimum time gap between two tasks. maxConnections
is the maximum number of tasks that can be running at the same time. Limiters are independent of each other. One common use case is setting different limiters for different proxies.
To help you better understand maxConnections
, here's an example. Say we have 10 tasks to do, rateLimit
is set to 2000 ms, maxConnections
is set to 3 and each task takes 10000 ms to finish. What happens will be as follows:
00'----start doing task1
02'----start doing task2
04'----start doing task3
10'----task1 done, start doing task4
12'----task2 done, start doing task5
...
Below is an example:
var Crawler = require("crawler");
var c = new Crawler({
maxConnections : 1,
rateLimit:2000,
callback : function (error, res, done) {
if(error){
console.error(error);
}else{
var $ = res.$;
console.log($('title').text());
}
done();
}
});
c.queue({
uri:"http://www.google.com",
limiter:"key1",
proxy:"http://user:pass@127.0.0.1:8080"
});
c.queue({
uri:"http://www.google.com",
limiter:"key2",
proxy:"http://user:pass@127.0.0.1:8082"
});
c.queue({
uri:"http://www.google.com",
limiter:"key3",
proxy:"http://user:pass@127.0.0.1:8081"
});
Options reference
You can pass these options to the Crawler() constructor if you want them to be global or as
items in the queue() calls if you want them to be specific to that item (overwriting global options)
This options list is a strict superset of mikeal's request options and will be directly passed to
the request() method.
Basic request options:
Callbacks:
callback(error, res, done)
: Function that will be called after a request was completed
error
: Errorres
: http.IncomingMessage A response of standard IncomingMessage includes $
and options
res.statusCode
: Number HTTP status code. E.G.200
res.body
: Buffer | String HTTP response content which could be a html page, plain text or xml document e.g.res.headers
: Object HTTP response headersres.request
: Request An instance of Mikeal's Request
instead of http.ClientRequest
res.request.uri
: urlObject HTTP request entity of parsed urlres.request.method
: String HTTP request method. E.G. GET
res.request.headers
: Object HTTP request headers
res.options
: Options of this task$
: jQuery Selector A selector for html or xml document.
done
: Function It must be called when you've done your work in callback.
Schedule options:
maxConnections
: Number Size of the worker pool (Default 10).rateLimit
: Number Number of milliseconds to delay between each requests (Default 0).priorityRange
: Number Range of acceptable priorities starting from 0 (Default 10).priority
: Number Priority of this request (Default 5).
Retry options:
retries
: Number Number of retries if the request fails (Default 3),retryTimeout
: Number Number of milliseconds to wait before retrying (Default 10000),
Server-side DOM options:
jQuery
: Boolean|String|Object Use cheerio
with default configrations to inject document if true or "cheerio". Or use customized cheerio
if an object with Parser options. Disable injecting jQuery selector if false. If you have memory leak issue in your project, use "whacko", an alternative parser,to avoid that. (Default true)
Charset encoding:
forceUTF8
: Boolean If true crawler will get charset from HTTP headers or meta tag in html and convert it to UTF8 if necessary. Never worry about encoding anymore! (Default true),incomingEncoding
: String With forceUTF8: true to set encoding manually (Default null) so that crawler will not have to detect charset by itself. For example, incomingEncoding : 'windows-1255'
. See all supported encodings
Cache:
skipDuplicates
: Boolean If true skips URIs that were already crawled, without even calling callback() (Default false). This is not recommended, it's better to handle outside Crawler
use seenreq
Other:
-
rotateUA
: Boolean If true, userAgent
should be an array and rotate it (Default false)
-
userAgent
: String|Array, If rotateUA
is false, but userAgent
is an array, crawler will use the first one.
-
referer
: String If truthy sets the HTTP referer header
Class:Crawler
Event: 'schedule'
Emitted when a task is being added to scheduler.
crawler.on('schedule',function(options){
options.proxy = "http://proxy:port";
});
Event: 'limiterChange'
Emitted when limiter has been changed.
Event: 'request'
Emitted when crawler is ready to send a request.
If you are going to modify options at last stage before requesting, just listen on it.
crawler.on('request',function(options){
options.qs.timestamp = new Date().getTime();
});
Event: 'drain'
Emitted when queue is empty.
crawler.on('drain',function(){
db.end();
});
crawler.queue(uri|options)
Enqueue a task and wait for it to be excuted.
crawler.queueSize
Size of queue, read-only
Working with Cheerio or JSDOM
Crawler by default use Cheerio instead of Jsdom. Jsdom is more robust but can be hard to install (espacially on windows) because of contextify.
Which is why, if you want to use jsdom you will have to build it, and require('jsdom')
in your own script before passing it to crawler. This is to avoid cheerio crawler user to build jsdom when installing crawler.
Working with Cheerio
jQuery: true
jQuery: 'cheerio'
jQuery: {
name: 'cheerio',
options: {
normalizeWhitespace: true,
xmlMode: true
}
}
These parsing options are taken directly from htmlparser2, therefore any options that can be used in htmlparser2
are valid in cheerio as well. The default options are:
{
normalizeWhitespace: false,
xmlMode: false,
decodeEntities: true
}
For a full list of options and their effects, see this and
htmlparser2's options.
source
Working with JSDOM
In order to work with JSDOM you will have to install it in your project folder npm install jsdom
, deal with compiling C++ and pass it to crawler.
var jsdom = require('jsdom');
var Crawler = require('crawler');
var c = new Crawler({
jQuery: jsdom
});
How to test
Install and run Httpbin
crawler use a local httpbin for testing purpose. You can install httpbin as a library from PyPI and run it as a WSGI app. For example, using Gunicorn:
$ pip install httpbin
$ gunicorn httpbin:app -b 127.0.0.1:8000 -w 6 --daemon
$ npm install && npm test
Alternative: Docker
After installing Docker, you can run:
$ docker build -t node-crawler .
$ docker run node-crawler sh -c "gunicorn httpbin:app -b 127.0.0.1:8000 -w 6 --daemon && cd /usr/local/lib/node_modules/crawler && npm install && npm test"
$ docker run -i -t node-crawler bash
Rough todolist
ChangeLog
See CHANGELOG