Crawl data from source

In [2]:
import urllib3

http = urllib3.PoolManager()


hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

globalRequest = 'https://www.usnews.com/education/best-global-universities/rankings?page={}'

htmlData = dict()
for i in range(1, 151):
    print(i, end=' ')
    html = http.request('GET', globalRequest.format(i), headers=hdr)
    htmlData[i] = html.data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 

Extract relevant information

In [6]:
import re
from bs4 import BeautifulSoup

uniInfo = []
for i in range(1, 151):
    soup = BeautifulSoup(htmlData[i], 'html.parser')
    resultNode = soup.find(id='resultsMain')

    for divNode in resultNode.findChildren('div', {'class' : 'sep'}):
        rankNode = divNode.findChildren('span', {'class':'rankscore-bronze'})[0]
        matchResult = re.search(r'#([0-9]*?)\s', rankNode.text)
        rank = int(matchResult.group(1))

        for node in divNode.findChildren('h2', {'class' : 'h-taut'}):
            aNode = node.findChildren('a')[0]
            name = aNode.text

        for node in divNode.findChildren('div', {'class' : 't-taut'}):
            cNode = node.findChildren('span')[0]
            region = cNode.text

        uniItem = {
            'name' : name,
            'region' : region,
            'global_ranking' : rank
        }

        uniInfo.append(uniItem)

A total of 1500 universities in the world

In [8]:
print(len(uniInfo))
print(uniInfo[0])
1500
{'name': 'Harvard University', 'region': 'United States', 'global_ranking': 1}
In [14]:
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter

allRegion = [item['region'] for item in uniInfo]
regionCounter = Counter(allRegion)

Region and number of universities on the chart

In [61]:
fig = plt.figure(figsize=(8, 16))
regionTop = regionCounter.most_common()
regionTopNames, regionTopCount = zip(*regionTop)
plt.barh(np.arange(len(regionTopNames)), regionTopCount)
plt.gca().invert_yaxis()
plt.yticks(np.arange(len(regionTopNames)), regionTopNames)
plt.ylim((len(regionTopNames)-0.5, -0.5))
plt.xlim((0, max(regionTopCount) + 40))
for i in range(len(regionTopCount)):
    plt.text(regionTopCount[i] + 5, i - 0.3, repr(regionTopCount[i]), ha='left', va='top')

Median ranking of each region (with number of institutions in the parenthesis)

In [83]:
fig = plt.figure(figsize=(8, 16))
# group world rankings by region
regionRanking = dict()
for key in regionTopNames:
    regionRanking[key] = []
rankTuples = [(item['region'], item['global_ranking']) for item in uniInfo]
for r, gr in rankTuples:
    regionRanking[r].append(gr)
regionMedian = [np.median(regionRanking[r]) for r in regionTopNames]
plt.barh(np.arange(len(regionTopNames)), regionMedian)
plt.gca().invert_yaxis()
plt.yticks(np.arange(len(regionTopNames)), regionTopNames)
plt.ylim((len(regionTopNames)-0.5, -0.5))
plt.xlim((0, max(regionMedian) + 180))
for i in range(len(regionTopCount)):
    plt.text(regionMedian[i] + 20, i - 0.3, '{} ({})'.format(int(regionMedian[i]), regionTopCount[i]),
             ha='left', va='top')

The distribution of world rankings within each region (color indicates world ranking)

In [147]:
from scipy.interpolate import interp1d

fig = plt.figure(figsize=(8, 20))

for i in range(len(regionTopNames)):
    rawRanking = regionRanking[regionTopNames[i]]
    if len(rawRanking) == 1:
        percentile = np.asarray([1.0])
    else:
        percentile = np.arange(len(rawRanking))/ (len(rawRanking) - 1)

    if percentile.size == 1:
        interpFunc = lambda x : np.asarray([rawRanking[0]] * x.size)
    else:
        interpFunc = interp1d(percentile, rawRanking)

    x = np.linspace(0.0, 1.0, 80)
    c = interpFunc(x)
    cbar = plt.scatter(x, [i] * x.size, 25, c, cmap='jet', marker='s', vmin=1, vmax=1500)



plt.gca().invert_yaxis()
plt.yticks(np.arange(len(regionTopNames)), regionTopNames)
plt.ylim((len(regionTopNames)-0.5, -0.5))
plt.xlim((0, 1.0))
plt.xlabel('Percentile within region')
plt.subplots_adjust(top=0.87)
barAx = plt.axes([0.1, 0.9, 0.8, 0.01])
plt.colorbar(cbar, cax=barAx, orientation='horizontal')
Out[147]:
<matplotlib.colorbar.Colorbar at 0x7f210160f828>
In [ ]: