-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscraper.js
More file actions
83 lines (75 loc) · 1.69 KB
/
Copy pathscraper.js
File metadata and controls
83 lines (75 loc) · 1.69 KB
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
var request = require('request'),
jsdom = require('jsdom'),
jquery = require('jquery'),
async = require('async');
// Create a jQuery object from the given html page
function createJqueryObject(page, cb) {
async.waterfall([
function(cb) {
jsdom.env({html: page, done: cb});
},
function(window, cb) {
cb(null, jquery.create(window));
}
], cb);
}
// Download the specified url and return a jQuery object
function loadUrlAsJquery(url, cb) {
async.waterfall([
function(cb) {
request(url, cb);
},
function(response, body, cb) {
createJqueryObject(body, cb);
}
], cb);
}
// Class for a scraper
function Scraper() {
this.addedUrls = {};
this.queue = [];
this.running = false;
this.doneCallback = null;
this.started = this.completed = 0;
}
Scraper.prototype.run = function(cb) {
this.doneCallback = cb;
this.running = true;
var that = this;
this.queue.forEach(function(url) {
that.parse(url);
});
};
/* Register the url; returns true if URL wasn't registered before */
Scraper.prototype.registerUrl = function(url) {
var ret = !this.addUrls[url];
this.addUrls[url] = true;
return ret;
};
Scraper.prototype.addUrl = function(url) {
if(this.registerUrl(url)) {
if(!this.running) {
this.queue.push(url);
} else {
this.parse(url);
}
}
};
Scraper.prototype.addUrls = function(urls) {
var that = this;
urls.forEach(function(url) {
that.addUrl(url);
});
};
Scraper.prototype.parse = function(url) {
this.started++;
var that = this;
loadUrlAsJquery(url, function(err, $) {
that.pageHandler(url, $);
that.completed++;
if(that.started == that.completed) {
that.doneCallback();
}
});
};
module.exports = Scraper;