怎么用python爬取世界大学排行数据
更新:HHH   时间:2023-1-7


今天小编给大家分享一下怎么用python爬取世界大学排行数据的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

数据获取

我们这里选取的就是上海交通大学的 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 = re.compile('flag.*/(.*?).png')
        country = re.findall(pattern,src)[0]
        lst.append(country)
    return lst
 

最后我们把得到的数据进行下处理,去除掉不需要的字段,再增加年份字段等

for i in range(2005, 2020):
    print('year', i)
    url = 'http://www.shanghairanking.com/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 文件

 


以上就是“怎么用python爬取世界大学排行数据”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注天达云行业资讯频道。

返回大数据教程...