Skip to content

Instantly share code, notes, and snippets.

@pietrovismara
Created January 5, 2017 21:39
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 pietrovismara/aae7e7bc90b76083e02df08ac4b2ea2e to your computer and use it in GitHub Desktop.
Save pietrovismara/aae7e7bc90b76083e02df08ac4b2ea2e to your computer and use it in GitHub Desktop.
Get google ranking for given keywords
const scavenger = require('scavenger');
module.exports = googleRanking;
/**
* @async
* @param {String} keywords
* @param {String} compareUrl
* @param {Number} pagesAmount
* @return {Number}
**/
function googleRanking(keywords, compareUrl, pagesAmount) {
pagesAmount = pagesAmount || 2;
const urls = scavenger.paginateUrl({
baseUrl: 'https://www.google.com/search?',
params: {
q: keywords,
start: 0
},
paginationParam: 'start',
limit: Math.round(pagesAmount) * 10,
step: 10
});
const extract = scavenger.createExtractor({
scope: 'div.rc',
fields: {
title: 'h3.r a',
url: {
selector: 'h3.r a',
attribute: 'href'
},
}
});
return scavenger.scrape(urls, { waitMs: 5000 }, extract)
.then((pages) => {
const results = [].concat.apply([], pages);
const ranking = _.findIndex(results, (res) => {
return res.url === compareUrl;
});
return ranking === -1 ? ranking : ranking + 1;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment