Skip to content

Commit

Permalink
feat: console colors
Browse files Browse the repository at this point in the history
  • Loading branch information
popstas committed Apr 15, 2020
1 parent ff88640 commit a78d9cb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 13 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Options:
--no-headless Show browser GUI while scan
--encoding <enc> Result csv encoding (default: "win1251")
--out-dir <dir> Output directory (default: ".")
--no-color No console colors
-V, --version output the version number
-h, --help display help for command
```
Expand Down
16 changes: 9 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ program
.option('--no-headless', `Show browser GUI while scan`)
.option('--encoding <enc>', `Result csv encoding`, 'win1251')
.option('--out-dir <dir>', `Output directory`, '.')
.option('--no-color', `No console colors`)
.name("sites-scraper")
.version(packageJson.version)
.usage("-u https://example.com")
Expand All @@ -39,13 +40,14 @@ async function start() {
await scrap_site(site, {
fields_preset: program.preset, // варианты: default, seo, headers, minimal
maxDepth: program.maxDepth, // глубина сканирования
maxConcurrency: 2 // параллельно открываемые вкладки
,skip_static: program.scipStatic // не пропускать подгрузку браузером статики (картинки, css, js)
,followSitemapXml: program.followXmlSitemap // чтобы найти больше страниц
,maxRequest: program.maxRequests // для тестов
,headless: program.headless // на десктопе открывает браузер визуально
,encoding: program.encoding // для Excel
,outDir: program.outDir // папка, куда сохраняются csv
maxConcurrency: 2, // параллельно открываемые вкладки
skip_static: program.scipStatic, // не пропускать подгрузку браузером статики (картинки, css, js)
followSitemapXml: program.followXmlSitemap, // чтобы найти больше страниц
maxRequest: program.maxRequests, // для тестов
headless: program.headless, // на десктопе открывает браузер визуально
encoding: program.encoding, // для Excel
outDir: program.outDir, // папка, куда сохраняются csv
color: program.color // раскрашивать консоль
});
}
}
Expand Down
22 changes: 16 additions & 6 deletions src/scrap-site.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ const url = require('url');
const DEBUG = true; // выключить, если не нужны console.log на каждый запрос (не будет видно прогресс)
const docs = ['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']; // можно дополнять

const color = {
reset: '\x1b[0m',
white: '\x1b[37m',
yellow: '\x1b[33m',
red: '\x1b[31m'
};

// запреты браузеру на подгрузку статики, ускоряет
let SKIP_IMAGES = true;
let SKIP_CSS = true;
Expand Down Expand Up @@ -64,6 +71,8 @@ module.exports = async (baseUrl, options = {}) => {
const csvPath = `${options.outDir}/${domain}.csv`; // файл вывода
let currentUrl = ''; // для хака с документами

if(!options.color) color.white = color.red = color.reset = color.yellow = '';

if (!options.fields_preset || !fields_presets[options.fields_preset]){
options.fields_preset = 'default';
}
Expand Down Expand Up @@ -158,7 +167,7 @@ module.exports = async (baseUrl, options = {}) => {

onSuccess: result => {
if (!result.result) return;
if (result.result.error) console.error('Error collect page data:', result.result.error);
if (result.result.error) console.error(`${color.red}Error collect page data: result.result.error${color.reset}`);
// console.log(`html_size: ${result.result.html_size}`);
},

Expand Down Expand Up @@ -193,7 +202,7 @@ module.exports = async (baseUrl, options = {}) => {

page.on('requestfailed', request => {
if (request.notHTTPS) {
console.error('mixed content: ', request.url());
console.error(`${color.red}mixed content: ${request.url()}${color.reset}`);
}
});

Expand Down Expand Up @@ -230,7 +239,7 @@ module.exports = async (baseUrl, options = {}) => {

const start = Date.now();

console.log(`Scrapping ${baseUrl}...`);
console.log(`${color.yellow}Scrapping ${baseUrl}...${color.reset}`);
let requestedCount = 0;

const crawler = await HCCrawler.launch(crawlerOptions);
Expand All @@ -241,19 +250,20 @@ module.exports = async (baseUrl, options = {}) => {
if (DEBUG) console.log(`${requestedCount} ${options.url} (${queueCount})`);
});
crawler.on('requestfailed', error => {
console.error(`Failed: ${error.options.url}`);
console.error(`${color.red}Failed: ${error.options.url}${color.reset}`);
});
crawler.on('requestdisallowed', options => {
console.error(`Disallowed in robots.txt: ${options.url}`);
console.error(`${color.yellow}Disallowed in robots.txt: ${options.url}${color.reset}`);
});
crawler.on('maxdepthreached', options => {
console.log(`Max depth reached`);
console.log(`${color.yellow}Max depth reached${color.reset}`);
});
await crawler.queue(baseUrl);
await crawler.onIdle();

const t = Math.round((Date.now() - start) / 1000);
const perPage = Math.round((t / requestedCount) * 100) / 100;
console.log(`${color.yellow}Saved to ${csvPath}${color.reset}`);
console.log(`Finish: ${t} sec (${perPage} per page)`);
await crawler.close();

Expand Down

0 comments on commit a78d9cb

Please sign in to comment.