-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathDynamicScraper.js
More file actions
226 lines (218 loc) · 5.95 KB
/
DynamicScraper.js
File metadata and controls
226 lines (218 loc) · 5.95 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
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
var phantomOrig = require('phantom'),
PhantomPoll = require('./PhantomPoll.js'),
phantom = phantomOrig,
AbstractScraper = require('./AbstractScraper'),
ScraperError = require('./ScraperError'),
PhantomWrapper = require('./PhantomWrapper');
/**
* A dynamic scraper. This is a very versatile and powerful. This
* solution is a little heavier and slower than the {@see StaticScraper}.
* This version uses phantomjs {@link http://phantomjs.org/}, and {@link https://github.com/sgentle/phantomjs-node}.
*
* @extends {AbstractScraper}
*/
var DynamicScraper = function(options) {
AbstractScraper.call(this);
/**
* Phantom instance.
*
* @type {?}
* @private
*/
this.ph = null;
/**
* Phantom's page.
*
* @type {?}
* @private
*/
this.page = null;
/**
* Phantom's options
*
* @type {?}
* @private
*/
this.options = {
onStdout: function() {},
onStderr: function() {},
dnodeOpts: {
weak: false
}
};
for (var key in options) { this.options[key] = options[key]; }
};
DynamicScraper.prototype = Object.create(AbstractScraper.prototype);
/**
* @override
* @inheritDoc
*/
DynamicScraper.prototype.loadBody = function(done) {
var that = this;
phantom.create('--load-images=no', that.options, function(ph) {
that.ph = ph;
ph.createPage(function(page) {
that.page = page;
page.setContent(that.body, that.url, function() {
that.inject(DynamicScraper.JQUERY_FILE, function(err) {
done(err ? new ScraperError('Couldn\'t inject jQuery into the page.') : undefined);
});
});
});
});
return this;
};
/**
* The scraper function has it's own scope (can't access outside its
* own scope), and only JSON serializable information can be return
* by the function. For more information {@link https://github.com/sgentle/phantomjs-node}.
*
* @param {!function(...?)} scraperFn Function to scrape the content.
* It receives the args as parameters, if passed.
* @param {!function(?)} callbackFn Function that receives the
* result of the scraping.
* @param {!Array=} args Additional arguments to pass to the scraping
* function. They must be JSON serializable.
* @param {!string=} stackTrace Stack trace to produce better error
* messages.
* @return {!AbstractScraper} This scraper.
* @override
* @public
*/
DynamicScraper.prototype.scrape = function(scraperFn, callbackFn, args, stackTrace) {
args = args || [];
args.unshift(scraperFn.toString());
args.unshift(function(result) {
if(result.error) {
callbackFn(DynamicScraper.generateMockErrorMessage(result.error, stackTrace), null);
} else {
callbackFn(null, result.result);
}
});
args.unshift(PhantomWrapper);
this.page.evaluate.apply(this.page, args);
return this;
};
/**
* Injects a javascript file into the page.
*
* @param {!string} file File to inject.
* @param {!function(!ScraperError=)} callback Function to be called
* when the file has injected. If the injection fails, then the
* first argument is not is a {@see ScraperError}.
* @public
*/
DynamicScraper.prototype.inject = function(file, callback) {
if (this.page) {
this.page.injectJs(file, function(success) {
if (success) {
callback();
} else {
callback(new ScraperError('Couldn\'t inject code, at "' + file + '".'));
}
});
} else {
throw new ScraperError('Couldn\'t inject code, at "' + file + '". The page has not been initialized yet.');
}
};
/**
* @override
* @inheritDoc
*/
DynamicScraper.prototype.close = function() {
if (this.page) {
this.page.close();
}
if (this.ph) {
this.ph.exit();
}
return this;
};
/**
* @override
* @inheritDoc
*/
DynamicScraper.prototype.clone = function() {
return new DynamicScraper();
};
/**
* Creates a dynamic scraper, wrapped around a scraper promise.
*
* @param {!string=} url If provided makes an HTTP GET request to the
* given URL.
* @return {!ScraperPromise} Scraper promise, with a dynamic scraper.
* @public
* @static
*/
DynamicScraper.create = function(url, options) {
return AbstractScraper.create(DynamicScraper, url, options);
};
/**
* Starts the factory. A factory should only be open once, and after
* it's open it must be closed with {@see DynamicScraper#closeFactory}.
* A factory makes so that there's only one instance of phantom at a
* time, which makes the creation/usage of dynamic scrapers much
* more efficient.
*
* @return {!DynamicScraper}
* @public
* @static
*/
DynamicScraper.startFactory = function() {
phantom = new PhantomPoll();
return DynamicScraper;
};
/**
* Closes the factory. For more information {@see DynamicScraper#closeFactory}
*
* @return {!DynamicScraper}
* @public
* @static
*/
DynamicScraper.closeFactory = function() {
if (phantom instanceof PhantomPoll) {
phantom.close();
}
phantom = phantomOrig;
return DynamicScraper;
};
/**
* Generates a mock error message that is similar to one produced
* by a function runned in node, and not phantomjs.
* @param {!Object} err Error object sent by Phantom.
* @param {!string} stackTrace Stack trace of where the promise was defined.
* @return {!Error} Error message.
* @private
* @static
*/
DynamicScraper.generateMockErrorMessage = function(err, stackTrace) {
var rg = /^\s{4}at ([^\s]+) \(([^\s]*)\:(\d+):(\d+)\)$/mg;
rg.exec(stackTrace);
var emsg = rg.exec(stackTrace);
var sob = emsg[1];
var sfile = emsg[2];
var sline = emsg[3];
var sc = emsg[4];
var line = Number(sline) + Math.max(err.line-1, 0);
var mock = new Error(err.message);
// Prevents the use of a property named 'line'!
delete err.line;
for(var x in err) {
mock[x] = err[x];
}
mock.stack = mock.stack.replace(/\t/g, ' ');
var ats = mock.stack.split('\n');
ats.unshift(' at ' + sob + ' (' + sfile + ':' + line + ':' + sc + ')');
ats.unshift('Error' + (err.message?': '+err.message:''));
mock.stack = ats.join('\n');
return mock;
};
/**
* Location of the jquery file.
*
* @type {!string}
* @private
* @static
*/
DynamicScraper.JQUERY_FILE = require.resolve('jquery');
module.exports = DynamicScraper;