Last active
August 29, 2015 14:05
-
-
Save frantzmiccoli/b8346fcba5543db2784b to your computer and use it in GitHub Desktop.
A small script that extract population and data from Wikipedia's list of biggest cities, it can be easily adapted for other pages and other informations.
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
// Run me in your console on http://en.wikipedia.org/wiki/List_of_cities_proper_by_population | |
// from http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery | |
var getTextNodesIn = function($el) { | |
return $($el.find(":not(iframe)").addBack().contents().filter(function() { | |
return this.nodeType == 3; | |
}).get(0)).text(); | |
}; | |
var rowsSelector = '#bodyContent .sortable.wikitable.jquery-tablesorter tr', | |
$rows = $(rowsSelector), | |
cityPopSelector = 'td:eq(3)', | |
cityCountrySelector = 'td:eq(7) a', | |
citiesData = []; | |
$rows.each(function(_, item) { | |
var $item = $(item), | |
$pop = $item.find(cityPopSelector), | |
pop = getTextNodesIn($pop).replace(/,/g, ''), | |
validPop = !(typeof(pop) === 'undefined') && (pop !== ''); | |
if (!validPop) { | |
return true; | |
} | |
var $country = $item.find(cityCountrySelector), | |
country = $country.attr('title'), | |
validCountry = !(typeof(country) === 'undefined') && (country !== ''); | |
if (!validCountry) { | |
return true; | |
} | |
var cityData = { | |
pop: pop, | |
country: country | |
}; | |
citiesData.push(cityData); | |
}); | |
console.log(citiesData); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment