数据获取
我们这里选取的就是上海交通大学的 ARWU 网站
该网站包含了历年的大学分数以及排名情况。
通过分析页面可以发现,通过 pandas 的 read_html 函数来获取相关信息是最为方便的
table = pd.read_html(url)
college = table[0] 同时我们还发现,大学所对应的国家数据是图片,所以需要特殊处理下
def get_country_name(html):
soup = BeautifulSoup(html,'lxml')
countries = soup.select('td > a > img')
lst = []
for i in countries:
src = i['src']
pattern = repile('flag.*/(.*?).png')
country = re.findall(pattern,src)[0]
lst.append(country)
return lst 最后我们把得到的数据进行下处理,去除掉不需要的字段,再增加年份字段等
for i in range(2005, 2022):
print('year', i)
url = 'www.shanghairanking/ARWU%s.html' % i
html = requests.get(url).content
table = pd.read_html(url)
college = table[0]
college.columns = ['world rank','university', 2,3, 'score', 5]
college.drop([2,3,5],axis = 1,inplace = True)
college['year'] = i
college['index_rank'] = college.index
college['index_rank'] = college['index_rank'].astype(int) + 1
college['country'] = get_country(html)
college.to_csv(r'College.csv', mode='a', encoding='utf_8_sig', header=True, index=0)这样,我们就得到了 College.csv 文件









