-
Notifications
You must be signed in to change notification settings - Fork 27
/
scrap-site.js
513 lines (442 loc) · 18.3 KB
/
scrap-site.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// see API - https://github.com/yujiosaka/headless-chrome-crawler/blob/master/docs/API.md#event-requeststarted
const fs = require('fs');
const path = require('path');
const {saveAsXlsx, saveAsJson, uploadJson, publishGoogleDrive, startViewer} = require(
'./actions');
const HCCrawler = require('@popstas/headless-chrome-crawler');
const CSVExporter = require('@popstas/headless-chrome-crawler/exporter/csv');
const url = require('url');
const {validateResults, getValidationSum} = require('./validate');
const {exec} = require('child_process');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
// поля описаны в API по ссылке выше
const fieldsPresets = require('./presets/scraperFields');
const color = require('./color');
const DEBUG = true; // выключить, если не нужны console.log на каждый запрос (не будет видно прогресс)
// запреты браузеру на подгрузку статики, ускоряет
let SKIP_IMAGES = true;
let SKIP_CSS = true;
let SKIP_JS = true;
// кол-во попыток выполнить actions
const finishTries = 5;
module.exports = async (baseUrl, options = {}) => {
const domain = url.parse(baseUrl).hostname;
const protocol = url.parse(baseUrl).protocol;
const csvPath = path.normalize(`${options.outDir}/${domain}.csv`);
const xlsxPath = path.normalize(`${options.outDir}/${domain}.xlsx`);
const jsonPath = path.normalize(`${options.outDir}/${domain}.json`);
let webPath;
if (!options.color) color.white = color.red = color.reset = color.yellow = '';
if (!options.fieldsPreset || !fieldsPresets[options.fieldsPreset]) {
options.fieldsPreset = 'default';
}
let fields = fieldsPresets[options.fieldsPreset];
// exclude fields
if (options.fieldsExclude && options.fieldsExclude.length > 0) {
fields = fields.filter(f => {
const fName = f.replace(/.*\./g, '');
return !options.fieldsExclude.includes(fName);
});
}
// custom fields
if (Object.keys(options.fields).length > 0) {
// console.log('options.fields: ', options.fields);
const newFields = Object.keys(options.fields).map(f => 'result.' + f);
fields = [...fields, ...newFields];
}
// lighthouse fields
if (options.lighthouse) {
for (let fName of fieldsPresets['lighthouse-all']) {
if (fields.indexOf(fName) === -1) {
fields.push(fName);
}
}
}
// skip static
if (options.skipStatic !== undefined) {
SKIP_IMAGES = SKIP_CSS = SKIP_JS = options.skipStatic;
}
// open second chrome for lighthouse
let lighthouseChrome;
if (options.lighthouse) {
const chromeFlags = ['--no-sandbox'];
if (options.headless) chromeFlags.push('--headless');
lighthouseChrome = await chromeLauncher.launch({chromeFlags});
}
const exporter = new CSVExporter({
file: csvPath,
fields: fields,
separator: ';',
});
let crawler;
const defaultOptions = {
allowedDomains: options.limitDomain ? [domain] : undefined,
skipRequestedRedirect: true, // all redirects marks as visited
depthPriority: false, // without it find not all pages
args: ['--no-sandbox'], // puppeteer freezes without it
exporter,
// url ignore rules
preRequest: options => {
// console.log(options.url);
if (options.url.match(/\.(jpg|jpeg|png|gif)/i)) return false; // картинки
if (options.url.match(/\?width=\d+&height=\d+/)) return false; // визитки, сотрудники
if (options.url.includes('?vi=y')) return false; // версия для слабовидящих
if (options.url.includes('gallery/?page=detail')) return false; // Битрикс Галерея 2.0
if (options.url.includes('/?lightbox=')) return false; // lightbox
if (options.url.includes('rk.php')) return false; // bitrix rk
if (options.url.includes('/?catalog_view=')) return false; // bitrix display
if (options.url.includes('/?SORT=')) return false; // bitrix sort
if (options.url.includes('/filter/clear/apply/')) return false; // bitrix filter
// if (options.url.match(/\?(category|age|usage|madein|season|brand)=/)) return false; // bitrix filter
// http scan while first page was https
if (url.parse(options.url).protocol != protocol) return false;
return true;
},
// сюда можно дописывать сборщики данных со страницы
// поля надо добавить в fields выше
evaluatePage: async () => {
try {
const customFields = await window.__customFields();
// console.log('window.__customFields(): ', JSON.stringify(customFields));
let domainParts = location.host.split('.');
const domain2level = domainParts.slice(domainParts.length - 2).
join('.');
const canonical = $('link[rel="canonical"]').attr('href');
const relUrl = window.location.href.replace(`${window.location.protocol}//${window.location.host}`, '');
const isCanonical = canonical ?
(canonical == decodeURI(window.location.href) ||
canonical == decodeURI(relUrl) ? 1 : 0) : '';
const result = {
request_time:
window.performance.timing.responseEnd -
window.performance.timing.requestStart,
title: $('title').text(),
h1: $('h1').text().trim(),
h1_count: $('h1').length,
h2_count: $('h2').length,
h3_count: $('h3').length,
h4_count: $('h4').length,
canonical_count: $('link[rel="canonical"]').length,
dom_size: document.getElementsByTagName('*').length,
head_size: document.head.innerHTML.length,
body_size: document.body.innerHTML.length,
html_size: document.head.innerHTML.length +
document.body.innerHTML.length,
text_ratio_percent: Math.round(
document.body.innerText.length / document.body.innerHTML.length *
100),
images: $('img').length,
images_without_alt: $('img:not([alt]').length,
images_alt_empty: $('img[alt=""]').length,
images_outer: $(
'img[src^="http"]:not([src^="/"]):not([src*="' + domain2level +
'"])').length,
links: $('a[href]:not([href^="javascript"]):not([href^="#"])').length,
links_inner: $(
'a[href^="/"], a[href*="' + domain2level + '"]').length,
links_outer: $(
'a[href]:not([href^="javascript"]):not([href^="#"]):not([href^="/"]):not([href*="' +
domain2level + '"])').length,
// links_absolute: $('').length,
description:
($('meta[name="description"]').attr('content') &&
$('meta[name="description"]').
attr('content').
split('\n').
join(' ')) ||
'',
keywords: $('meta[name="keywords"]').attr('content'),
canonical: canonical,
is_canonical: isCanonical,
og_title: $('meta[property="og:title"]').attr('content'),
og_image: $('meta[property="og:image"]').attr('content'),
schema_types: $.unique($('[itemtype]').
map((i, item) => $(item).
attr('itemType').
replace(/https?:\/\/schema\.org\//, ''))).toArray().join(', '),
};
for (let name in customFields) {
result[name] = eval(customFields[name].replace(/`/g, '\''));
// if(name == 'section') result[name] = $('.views-field.views-field-field-section a').text();
}
return result;
} catch (e) {
return {
error: JSON.stringify(e),
};
}
},
onSuccess: result => {
if (!result.result) return;
if (result.result.error) {
const msg = `${color.red}Error collect page data: result.result.error${color.reset}`;
console.error(msg);
}
// console.log(`html_size: ${result.result.html_size}`);
},
customCrawl: async (page, crawl, crawler) => {
// You can access the page object before requests
await page.setRequestInterception(true);
await page.setBypassCSP(true);
//page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('__customFields', () => {
return options.fields;
});
let mixedContentUrl = '';
// это событие срабатывает, когда chrome подгружает статику на странице (и саму страницу)
page.on('request', request => {
//console.log('request.url(): ', request.url());
// check for mixed content, thanks to https://github.com/busterc/mixed-content-crawler/
if (protocol == 'https:' &&
['image', 'stylesheet', 'script'].includes(request.resourceType()) &&
request.url().match(/^http:/)) {
request.notHTTPS = true;
mixedContentUrl = request.url();
return request.abort();
}
const isDoc = options.docsExtensions.some(
ext => request.url().includes(`.${ext}`));
if (isDoc) {
// досюда как-то доходит
request.abort();
} else if (SKIP_IMAGES && request.resourceType() == 'image') {
request.abort();
} else if (SKIP_CSS && request.resourceType() == 'stylesheet') {
request.abort();
} else if (SKIP_JS && request.resourceType() == 'script') {
request.abort();
} else {
request.continue();
}
});
page.on('requestfailed', request => {
if (request.notHTTPS) {
console.error(
`${color.red}mixed content: ${request.url()}${color.reset}`);
} else {
const isStatic = ['image', 'script', 'stylesheet'].includes(request.resourceType());
if (!isStatic) console.log('Request failed: ', request.url() + ' ' + request.failure().errorText);
}
});
/*page.on('error', function(err) {
console.error(`${color.red}Page error:${color.reset} ` + err.toString());
});*/
/*page.on('close', function() {
console.error(`${color.red}Page closed${color.reset} `);
});*/
/*page.on('pageerror', function(err) {
console.error(`${color.red}pegeerror:${color.reset} ` + err.toString());
});*/
// console.log('co '+ crawler._options.url);
// костыль, который возвращает фейково обойдённый документ, если он признан документом
// нужно, чтобы доки не сканировались (выдают ошибку), но при этом добавлялись в csv
// т.к. в этом контексте нет текущего урла, он задаётся в глобал через событие requeststarted
const isDoc = crawler._options.url && options.docsExtensions.some(
ext => crawler._options.url.includes(`.${ext}`));
if (isDoc) {
return {
options: {},
depth: 0,
previousUrl: '',
response: {
url: crawler._options.url,
},
redirectChain: [],
result: {},
screenshot: null,
cookies: [],
links: [],
};
}
// The result contains options, links, cookies and etc.
const result = await crawl();
if (options.lighthouse) {
const opts = {
// extends: 'lighthouse:default',
/*onlyAudits: [
'first-meaningful-paint',
'speed-index',
'first-cpu-idle',
'interactive',
],*/
// onlyCategories : [ 'performance'/*, 'pwa', 'accessibility', 'best-practices', 'seo'*/ ],
port: lighthouseChrome.port,
locale: options.lang,
};
const res = await lighthouse(crawler._options.url, opts);
const data = JSON.parse(res.report);
const audits = [
'first-contentful-paint',
'speed-index',
'largest-contentful-paint',
'interactive',
'total-blocking-time',
'cumulative-layout-shift',
];
const categories = [
'performance',
'accessibility',
'best-practices',
'seo',
'pwa'];
const lighthouseData = {
scores: {},
};
const fieldConfigs = []; // для генерации конфига полей
for (let auditName of audits) {
if (!data.audits[auditName]) continue;
lighthouseData[auditName] = parseInt(
data.audits[auditName].numericValue);
}
for (let categoryId of categories) {
if (!data.categories[categoryId]) continue;
// lighthouse.scores
lighthouseData.scores[categoryId] = parseInt(
data.categories[categoryId].score * 100);
// all audits
for (let auditRef of data.categories[categoryId].auditRefs) {
let value;
const auditName = auditRef.id;
const audit = data.audits[auditName];
if (audit.numericValue) value = parseInt(audit.numericValue);
else value = audit.score;
lighthouseData[auditName] = value;
// add to sheet fields
if (options.fieldsPreset === 'lighthouse-all') {
const fieldId = 'lighthouse.' + auditName;
if (fields.indexOf(fieldId) === -1) {
fields.push(fieldId);
}
}
// generate field config
const fieldConfig = {
name: 'lighthouse_' + audit.id,
comment: audit.title,
description: audit.description,
groups: ['# Lighthouse: ' + data.categories[categoryId].title],
type: 'integer',
};
if (auditRef.group) {
const groupTitle = data.categories[categoryId].title + ': ' +
data.categoryGroups[auditRef.group].title;
fieldConfig.groups.push(groupTitle);
// fieldConfig.groups = [groupTitle];
}
fieldConfigs.push(fieldConfig);
}
}
result.lighthouse = lighthouseData;
// console.log(JSON.stringify(fieldConfigs)); // copy to fields.js
// console.log(lighthouseData);
}
result.result.mixed_content_url = mixedContentUrl;
if (result.response.url) result.response.url = decodeURI(
result.response.url);
// console validate output
// was in onSuccess(), but causes exception on docs
const msgs = [];
const validate = validateResults(result, fields); // TODO: fields declared implicitly
for (let name in validate) {
const res = validate[name];
const msgColor = {warning: color.yellow, error: color.red}[res.type];
msgs.push(`${name}: ${msgColor}${res.msg}${color.reset}`);
}
if (msgs.length > 0) console.log(msgs.join(', '));
// You can access the page object after requests
result.content = await page.content();
// You need to extend and return the crawled result
return result;
},
};
const crawlerOptions = {...defaultOptions, ...options};
// start
const start = Date.now();
console.log(`${color.yellow}Scrapping ${baseUrl}...${color.reset}`);
let requestedCount = 0;
try {
crawler = await HCCrawler.launch(crawlerOptions);
} catch (e) {
console.log(e);
}
crawler.on('requeststarted', async options => {
const queueCount = await crawler.queueSize();
requestedCount = crawler.requestedCount() + 1;
if (DEBUG) console.log(
`${requestedCount} ${decodeURI(options.url)} (${queueCount})`);
});
crawler.on('requestfailed', error => {
console.error(
`${color.red}Failed: ${decodeURI(error.options.url)}${color.reset}`);
});
crawler.on('requestdisallowed', options => {
console.error(`${color.yellow}Disallowed in robots.txt: ${decodeURI(
options.url)}${color.reset}`);
});
crawler.on('maxdepthreached', options => {
console.log(`${color.yellow}Max depth reached${color.reset}`);
});
crawler.on('maxrequestreached', options => {
console.log(
`\n\n${color.yellow}Max requests reached\nPlease, ignore this error:${color.reset}`);
});
await crawler.queue(baseUrl);
await crawler.onIdle();
await crawler.close();
// after scan
const t = Math.round((Date.now() - start) / 1000);
const perPage = Math.round((t / requestedCount) * 100) / 100;
// close lighthouse's chrome
await chromeLauncher.killAll();
const outValidationSummary = () => {
const sum = getValidationSum();
if (Object.entries(sum).length === 0) return;
console.log(`\n\n${color.white}Validation summary:${color.reset}`);
for (let colName in sum) {
console.log(`\n${color.white}${colName}:${color.reset}`);
for (let res of sum[colName]) {
const msgColor = {warning: color.yellow, error: color.red}[res.type];
console.log(`${msgColor}${res.msg}${color.reset}\t${res.url}`);
}
}
};
const finishScan = async () => {
console.log('');
if (options.xlsx) {
saveAsXlsx(csvPath, xlsxPath);
if (options.gdrive) await publishGoogleDrive(xlsxPath);
if (options.openFile) exec(`"${xlsxPath}"`);
}
if (options.json) {
await saveAsJson(csvPath, jsonPath, options.lang, options.preset);
if (!options.removeJson) console.log('Saved to ' + jsonPath);
if (options.upload) webPath = await uploadJson(jsonPath, options);
// if (options.gdrive) webPath = await publishGoogleDrive(jsonPath);
await startViewer(jsonPath, webPath);
if (options.removeJson) fs.unlinkSync(jsonPath);
}
if (options.removeCsv) fs.unlinkSync(csvPath);
const mins = Number(t / 60).toFixed(1);
console.log(`Finish: ${mins} mins (${perPage} sec per page)`);
};
outValidationSummary();
const tryFinish = async (tries) => {
try {
await finishScan();
} catch (e) {
if (e.code == 'EBUSY') {
let msg = `${color.red}${xlsxPath} is busy`;
if (tries > 0) msg += ', please close file in 10 seconds!';
console.error(msg);
if (tries > 0) {
setTimeout(async () => {
await tryFinish(tries - 1);
}, 10000);
}
} else {
console.error(e);
}
}
};
await tryFinish(finishTries);
};