Created
January 5, 2017 21:39
-
-
Save pietrovismara/aae7e7bc90b76083e02df08ac4b2ea2e to your computer and use it in GitHub Desktop.
Get google ranking for given keywords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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