Skip to content

Instantly share code, notes, and snippets.

@quanon
Created May 23, 2019 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quanon/11151e2959c8c5c41160cab0d9a30bb9 to your computer and use it in GitHub Desktop.
Save quanon/11151e2959c8c5c41160cab0d9a30bb9 to your computer and use it in GitHub Desktop.
count_of_search_results
const puppeteer = require('puppeteer');
const columnify = require('columnify');
const url = 'https://www.google.co.jp/';
const args = process.argv.slice(2);
(async () => {
const browser = await puppeteer.launch();
let results = await Promise.all(args.map(async (word) => {
const page = await browser.newPage();
await page.goto(url);
await page.type('input[name="q"]', `"${word}"`);
await page.keyboard.press('Enter');
await page.waitForNavigation();
const text = await page.evaluate(() => {
const element = document.querySelector('#resultStats');
return element ? element.textContent : '';
});
const match = text.match(/[\d,]+/);
const rawCount = (match || ['0'])[0];
const count = Number(rawCount.replace(/,/g, ''));
return { word, rawCount, count }
}));
results = results.sort((a, b) => {
if (a.count < b.count) return 1;
if (a.count > b.count) return -1;
return 0;
})
console.log(columnify(results, {
columns: ['word', 'rawCount'],
config: {
word: { headingTransform: () => '単語' },
rawCount: { headingTransform: () => '件数' }
}
}));
await browser.close();
})();
{
"private": true,
"dependencies": {
"columnify": "^1.5.4",
"puppeteer": "1.16.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment