forked from safonovpro/node-html-crawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crawler.js
344 lines (275 loc) · 10.6 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
const EventEmitter = require('events');
const http = require('http');
const https = require('https');
const url = require('url');
const punycode = require('punycode');
class Crawler extends EventEmitter {
constructor(config) {
super();
this.config = {
protocol: 'http:',
domain: 'example.com',
limitForConnections: 10,
limitForRedirects: 5,
timeout: 300,
headers: { 'User-Agent': 'Mozilla/5.0' },
};
if (typeof config === 'string') {
this.config.domain = config.trim();
} else if (typeof config === 'object') {
this.config = { ...this.config, ...config };
}
this.config.domain = punycode.toASCII(this.config.domain);
this.config.startUrl = `${this.config.protocol}//${this.config.domain}/`;
// Other params
this.countOfConnections = 0;
this.waitingOfConnection = 0;
this.startUrl = `${this.config.protocol}//${this.config.domain}/`;
this.foundLinks = new Set();
this.countOfProcessedUrls = 0;
this.stop = 0;
}
crawl(urlString = this.startUrl, countOfRedirects = 0) {
// If urlString has not been processed before
if (!this.foundLinks.has(urlString) && countOfRedirects < this.config.limitForRedirects) {
const currentUrl = urlString;
if (this.countOfConnections < this.config.limitForConnections) {
this.foundLinks.add(currentUrl);
this.getDataByUrl(currentUrl)
.then((headers) => {
if (headers.statusCode === 200 && /^text\/html/.test(headers.headers['content-type'])) {
this.getDataByUrl(currentUrl, 'GET')
.then((result) => {
for (let i = 0; i < result.links.length; i++) {
if (this.stop)
return;
if (result.links[i].url)
this.crawl(result.links[i].url)
}
this.generateEvents('data', { currentUrl, result });
}).catch((error) => {
this.generateEvents('error', { currentUrl, error });
});
} else if (/30\d/.test(headers.statusCode)) {
const { location } = headers.headers;
const nextUrl = this.getInterestingFullUrl(location, currentUrl);
headers.links.push({ href: location, url: nextUrl });
if (nextUrl) {
this.crawl(nextUrl, countOfRedirects + 1);
}
this.generateEvents('data', { currentUrl, result: headers });
} else {
this.generateEvents('data', { currentUrl, result: headers });
}
}).catch((error) => {
this.generateEvents('error', { currentUrl, error });
});
} else {
this.waitingOfConnection += 1;
setTimeout(() => {
this.waitingOfConnection -= 1;
this.crawl(currentUrl, countOfRedirects);
}, this.config.timeout);
}
}
}
getInterestingFullUrl(urlString, parentUrl, parentTagBaseHrefValue) {
const urlObject = url.parse(urlString);
let result = false;
if (!this.isInterestingUrl(urlString)) return result;
if (urlObject.protocol && urlObject.hostname) {
result = `${urlObject.protocol}//${urlObject.host}${urlObject.path}`;
} else if (parentUrl !== undefined) {
const parentUrlObject = url.parse(parentUrl);
if (!urlObject.protocol && /^\/\//.test(urlObject.pathname)) {
result = parentUrlObject.protocol + urlObject.path;
} else if (parentTagBaseHrefValue !== undefined) {
result = `${parentTagBaseHrefValue.replace(/\/$/, '')}/${urlObject.path.replace(/^\//, '')}`;
} else if (/^\//.test(urlObject.pathname)) {
result = `${parentUrlObject.protocol}//${parentUrlObject.host}${urlObject.path}`;
} else {
result = `${parentUrlObject.protocol}//${parentUrlObject.host}${parentUrlObject.path.replace(/[^/]*$/, '')}${urlObject.path.replace(/^\.\//, '')}`;
}
}
result = Crawler.removeDotsInUrl(result);
result = Crawler.smartDecodeUrl(result);
return result;
}
isInterestingUrl(urlString) {
const urlObject = url.parse((/^\/\//.test(urlString.trim()) ? `http:${urlString}` : urlString));
let result = false;
if (/^https?:/.test(urlObject.protocol)) {
if (urlObject.hostname) {
/* Accept image URL hosted somewhere else. */
if (urlObject.pathname.endsWith('.jpg') || urlObject.pathname.endsWith('.jpeg')
|| urlObject.pathname.endsWith('.png'))
result = true;
/* Non-image URL must be from same domain. */
if (urlObject.hostname.replace(/^w{3}\./, '') === this.config.domain.replace(/^w{3}\./, '')) {
result = true;
}
}
}
else if (!urlObject.protocol && !urlObject.host && urlObject.path) {
result = true;
}
return result;
}
static smartDecodeUrl(notDecodeUrl) {
const urlArray = notDecodeUrl.split('/');
let result = '';
for (let i = 3; i < urlArray.length; i += 1) {
const partPath = urlArray[i].split('').map((val) => ((val === '%') ? val : encodeURI(val))).join('');
result += `/${partPath}`;
}
result = `${urlArray[0]}//${urlArray[2]}${result}`;
return result;
}
/* Go back to parent directory like in Linux bash. */
static removeDotsInUrl(urlWithDots) {
const urlArray = urlWithDots.split('/');
let countOfDotted = 0;
let result = '';
for (let i = urlArray.length - 1; i > 2; i -= 1) {
if (urlArray[i] === '..') {
countOfDotted += 1;
} else if (countOfDotted === 0) {
result = `${urlArray[i]}${(i === urlArray.length - 1) ? '' : '/'}${result}`;
} else {
countOfDotted -= 1;
}
}
result = `${urlArray[0]}//${urlArray[2]}/${result}`;
return result;
}
getDataByUrl(urlString, method = 'HEAD') {
const urlObject = url.parse(urlString);
const options = {
host: urlObject.hostname,
port: (urlObject.port) ? urlObject.port : 80,
path: urlObject.path,
method,
headers: this.config.headers,
};
let reqModule = http;
if (urlObject.protocol === 'https:') {
reqModule = https;
options.port = (urlObject.port) ? urlObject.port : 443;
}
this.countOfConnections += 1;
return new Promise((resolve, reject) => {
const request = reqModule.request(options, (response) => {
let body = '';
response.setEncoding('utf8');
response.on('data', (chunk) => { body += chunk; });
response.on('end', () => {
this.countOfConnections -= 1;
resolve({
requestMethod: method,
statusCode: response.statusCode,
headers: response.headers,
body,
links: (response.statusCode === 200 && /^text\/html/.test(response.headers['content-type'])) ? this.getUrlsOnHtml(urlString, body) : [],
});
});
});
request.on('error', (error) => {
this.countOfConnections -= 1;
reject(error);
});
request.end();
});
}
getUrlsOnHtml(currentUrl, html) {
const base = Crawler.getTagsHref('base', html)[0];
const result = [];
Crawler.getTagsBruteLinks(html).forEach((href) => {
if (result.find((value) => value.href === href) === undefined) {
result.push({
href,
url: this.getInterestingFullUrl(href, currentUrl, base),
});
}
});
return result;
}
static getTagsHref(tagName, html) {
const htmlWithoutComments = html.replace(/<!--(?:(?!-->)[\s\S])*-->/g, '');
const reg = new RegExp(`<${tagName}\\s*[^>]*>`, 'gi');
const foundTags = htmlWithoutComments.match(reg) || [];
const hrefs = [];
foundTags
.map((val) => val.replace(new RegExp(`(^<${tagName}\\s*|\\s*\\/?>$)`, 'gi'), '').trim())
.filter((val) => val.search(/(\s|^)href=/) > -1)
.forEach((val) => {
let strAttrs = val;
let commas = false;
let endChar = /(\s|$)/;
const hrefPos = strAttrs.search(/(\s|^)href=/);
strAttrs = (hrefPos) ? strAttrs.slice(hrefPos + 6) : strAttrs.slice(hrefPos + 5);
if (/('|")/.test(strAttrs[0])) {
[commas] = strAttrs;
endChar = commas;
strAttrs = strAttrs.slice(1);
}
hrefs.push(strAttrs.slice(0, strAttrs.search(endChar)));
});
return hrefs;
}
static getTagsBruteLinks(html) {
const htmlWithoutComments = html.replace(/<!--(?:(?!-->)[\s\S])*-->/g, '');
const reg = new RegExp(`<((a)|(img))\\s*[^>]*>`, 'gi');
const foundTags = htmlWithoutComments.match(reg) || [];
const hrefs = [];
foundTags
.map((val) => val.replace(new RegExp(`(^<((a)|(img))\\s*|\\s*\\/?>$)`, 'gi'), '').trim())
.filter((val) => val.search(/(\s|^)((href)|(src))=/) > -1)
.forEach((val) => {
let strAttrs = val;
let commas = false;
let endChar = /(\s|$)/;
let startPos = strAttrs.search(/^(href)=/);
/* If it's a href="" from the start of string. */
if (startPos != -1)
strAttrs = strAttrs.slice(startPos + 5);
else {
startPos = strAttrs.search(/\s(href)=/);
/* If it's a href="" from the middle with space before. */
if (startPos != -1)
strAttrs = strAttrs.slice(startPos + 6);
else {
startPos = strAttrs.search(/^(src)=/);
/* If it's a src="" from the start of string. */
if (startPos != -1)
strAttrs = strAttrs.slice(startPos + 4);
else {
startPos = strAttrs.search(/\s(src)=/);
/* If it's a src="" from the middle with space before. */
if (startPos != -1)
strAttrs = strAttrs.slice(startPos + 5);
}
}
}
if (/('|")/.test(strAttrs[0])) {
[commas] = strAttrs;
endChar = commas;
strAttrs = strAttrs.slice(1);
}
hrefs.push(strAttrs.slice(0, strAttrs.search(endChar)));
});
return hrefs;
}
generateEvents(eventsType, data) {
this.countOfProcessedUrls += 1;
if (eventsType === 'data' && !this.stop) {
this.emit('data', { url: data.currentUrl, result: data.result });
} else if (eventsType === 'error') {
this.emit('error', new Error(`Error in ${data.currentUrl}: ${data.error}`));
}
if (this.waitingOfConnection === 0 && this.countOfProcessedUrls === this.foundLinks.size) this.emit('end');
}
searchForceStop() {
this.stop = 1;
}
}
module.exports = Crawler;