html5深圳网站开发,专业网站建设企业,做淘客网站需要备案,站长工具天美传媒一、前言
QS世界大学排名是全球最具影响力的大学排名之一#xff0c;无论是留学选校、学术研究还是高校竞争力分析#xff0c;都有重要参考价值。本文将手把手教你用Python完成QS排名的数据爬取、清洗、分析与可视化#xff0c;从0到1实现完整的数据分析流程#xff0c;即使…一、前言QS世界大学排名是全球最具影响力的大学排名之一无论是留学选校、学术研究还是高校竞争力分析都有重要参考价值。本文将手把手教你用Python完成QS排名的数据爬取、清洗、分析与可视化从0到1实现完整的数据分析流程即使是Python新手也能轻松上手。分析目标爬取2025年QS世界大学排名核心数据排名、学校名称、国家/地区、总分等清洗数据处理缺失值、异常值分析核心维度TOP50高校国家分布、不同国家TOP100数量、总分分布等用可视化图表直观展示分析结果。二、环境准备首先安装所需Python库打开终端执行pipinstallrequests beautifulsoup4 pandas matplotlib lxmlrequests发送HTTP请求爬取网页数据beautifulsoup4解析HTML页面提取目标数据pandas数据清洗与分析matplotlib数据可视化lxml高效的HTML解析器。三、数据爬取本文选择爬取QS官网2025年世界大学综合排名公开可访问页面核心思路发送请求→解析页面→提取字段→存储为DataFrame。完整爬取代码importrequestsfrombs4importBeautifulSoupimportpandasaspdimporttime# 配置请求头模拟浏览器访问避免反爬headers{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Accept-Language:zh-CN,zh;q0.9,en;q0.8}# 存储所有数据的列表qs_data[]# QS2025排名页面分页爬取这里爬取前100名可按需扩展base_urlhttps://www.topuniversities.com/rankings/qs-world-university-rankings/2025?page{}# 爬取前10页每页10条共100条forpageinrange(1,11):try:# 发送请求urlbase_url.format(page)responserequests.get(url,headersheaders,timeout10)response.raise_for_status()# 抛出HTTP错误soupBeautifulSoup(response.text,lxml)# 解析页面# 定位排名数据行rank_rowssoup.find_all(div,class_row indx)forrowinrank_rows:# 提取排名处理并列排名如10rank_elemrow.find(div,class_rank)rankrank_elem.get_text(stripTrue)ifrank_elemelseNone# 提取学校名称name_elemrow.find(div,class_uni-name)universityname_elem.get_text(stripTrue)ifname_elemelseNone# 提取国家/地区country_elemrow.find(div,class_location)countrycountry_elem.get_text(stripTrue)ifcountry_elemelseNone# 提取总分score_elemrow.find(div,class_overall-score-span)scorescore_elem.get_text(stripTrue)ifscore_elemelseNone# 存储数据qs_data.append({排名:rank,学校名称:university,国家/地区:country,总分:score})print(f第{page}页数据爬取完成已获取{len(qs_data)}条记录)time.sleep(1)# 延迟1秒避免请求过快被封IPexceptExceptionase:print(f第{page}页爬取失败{str(e)})continue# 转换为DataFramedfpd.DataFrame(qs_data)# 保存原始数据到CSV可选df.to_csv(qs2025_rank_raw.csv,indexFalse,encodingutf-8-sig)print(原始数据爬取完成已保存为qs2025_rank_raw.csv)print(原始数据前5行)print(df.head())爬取说明若爬取失败可检查User-Agent是否为最新替换为自己浏览器的UAQS官网页面结构可能微调需根据实际HTML结构修改class名称爬取更多数据可修改分页范围如range(1, 51)爬取前500名。四、数据清洗爬取的原始数据可能存在缺失值、格式异常如总分是字符串、排名含“”需清洗后才能分析。清洗代码# 加载原始数据若已爬取可直接加载dfpd.read_csv(qs2025_rank_raw.csv,encodingutf-8-sig)# 1. 处理缺失值删除关键字段缺失的行dfdf.dropna(subset[排名,学校名称,国家/地区,总分])print(f删除缺失值后剩余数据量{len(df)})# 2. 清洗排名字段去除“”转换为整数df[排名]df[排名].str.replace(,).astype(int)# 3. 清洗总分字段转换为浮点数处理空值/非数字defclean_score(score):try:returnfloat(score)except:returnNonedf[总分]df[总分].apply(clean_score)# 删除总分仍为None的行dfdf.dropna(subset[总分])# 4. 去重按排名去重避免重复爬取dfdf.drop_duplicates(subset[排名],keepfirst)# 5. 重置索引dfdf.reset_index(dropTrue)# 保存清洗后的数据df.to_csv(qs2025_rank_clean.csv,indexFalse,encodingutf-8-sig)print(数据清洗完成已保存为qs2025_rank_clean.csv)print(清洗后数据前5行)print(df.head())# 基本数据信息print(\n数据基本信息)print(df.info())print(\n数据统计描述)print(df.describe())五、核心数据分析与可视化5.1 配置可视化环境解决中文显示问题importmatplotlib.pyplotasplt# 设置中文字体Windows系统plt.rcParams[font.sans-serif][SimHei]# 解决负号显示问题plt.rcParams[axes.unicode_minus]False# 设置图表风格plt.style.use(ggplot)5.2 分析1TOP50高校国家/地区分布# 筛选TOP50数据top50df[df[排名]50]# 统计国家/地区数量country_counttop50[国家/地区].value_counts()# 绘制柱状图plt.figure(figsize(12,6))country_count.plot(kindbar,colorsteelblue)plt.title(2025 QS世界大学排名TOP50 - 国家/地区分布,fontsize14)plt.xlabel(国家/地区,fontsize12)plt.ylabel(高校数量,fontsize12)plt.xticks(rotation45)plt.tight_layout()# 调整布局避免文字重叠plt.savefig(top50_country_dist.png,dpi300)plt.show()# 输出统计结果print(TOP50高校国家/地区分布)print(country_count)5.3 分析2主要国家TOP100高校数量对比# 筛选TOP100数据top100df[df[排名]100]# 筛选主要国家可按需调整main_countries[United States,United Kingdom,China,Japan,Germany,Canada,Australia]top100_maintop100[top100[国家/地区].isin(main_countries)]country_count_top100top100_main[国家/地区].value_counts()# 绘制饼图plt.figure(figsize(10,10))plt.pie(country_count_top100.values,labelscountry_count_top100.index,autopct%1.1f%%,startangle90,colorsplt.cm.Set3.colors)plt.title(2025 QS世界大学排名TOP100 - 主要国家占比,fontsize14)plt.tight_layout()plt.savefig(top100_country_pie.png,dpi300)plt.show()print(主要国家TOP100高校数量)print(country_count_top100)5.4 分析3TOP100高校总分分布# 绘制直方图plt.figure(figsize(10,6))plt.hist(top100[总分],bins15,colorlightcoral,edgecolorblack)plt.title(2025 QS世界大学排名TOP100 - 总分分布,fontsize14)plt.xlabel(总分,fontsize12)plt.ylabel(高校数量,fontsize12)plt.axvline(top100[总分].mean(),colorred,linestyle--,labelf平均分{top100[总分].mean():.2f})plt.legend()plt.tight_layout()plt.savefig(top100_score_dist.png,dpi300)plt.show()# 输出总分统计print(TOP100高校总分统计)print(f平均分{top100[总分].mean():.2f})print(f最高分{top100[总分].max():.2f})print(f最低分{top100[总分].min():.2f})print(f中位数{top100[总分].median():.2f})5.5 分析4中国高校大陆港澳台表现# 筛选中国高校大陆、中国香港、中国台湾、中国澳门china_unisdf[df[国家/地区].str.contains(China,naFalse)]# 按排名排序china_unis_sortedchina_unis.sort_values(排名)print(2025 QS排名中中国高校TOP100)print(china_unis_sorted[china_unis_sorted[排名]100][[排名,学校名称,国家/地区,总分]])# 绘制中国高校TOP100的排名与总分散点图china_top100china_unis_sorted[china_unis_sorted[排名]100]plt.figure(figsize(10,6))plt.scatter(china_top100[排名],china_top100[总分],colordarkgreen,s80)# 添加学校名称标注foridx,rowinchina_top100.iterrows():plt.annotate(row[学校名称],(row[排名],row[总分]),fontsize8,haright)plt.title(2025 QS排名TOP100 - 中国高校排名vs总分,fontsize14)plt.xlabel(排名,fontsize12)plt.ylabel(总分,fontsize12)plt.tight_layout()plt.savefig(china_unis_scatter.png,dpi300)plt.show()六、完整代码整合将以上步骤整合为一个完整脚本方便一键运行importrequestsfrombs4importBeautifulSoupimportpandasaspdimporttimeimportmatplotlib.pyplotasplt# 1. 环境配置 # 可视化中文配置plt.rcParams[font.sans-serif][SimHei]plt.rcParams[axes.unicode_minus]Falseplt.style.use(ggplot)# 请求头headers{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Accept-Language:zh-CN,zh;q0.9,en;q0.8}# 2. 数据爬取 defcrawl_qs_rank():qs_data[]base_urlhttps://www.topuniversities.com/rankings/qs-world-university-rankings/2025?page{}forpageinrange(1,11):try:urlbase_url.format(page)responserequests.get(url,headersheaders,timeout10)response.raise_for_status()soupBeautifulSoup(response.text,lxml)rank_rowssoup.find_all(div,class_row indx)forrowinrank_rows:rankrow.find(div,class_rank).get_text(stripTrue)ifrow.find(div,class_rank)elseNoneuniversityrow.find(div,class_uni-name).get_text(stripTrue)ifrow.find(div,class_uni-name)elseNonecountryrow.find(div,class_location).get_text(stripTrue)ifrow.find(div,class_location)elseNonescorerow.find(div,class_overall-score-span).get_text(stripTrue)ifrow.find(div,class_overall-score-span)elseNoneqs_data.append({排名:rank,学校名称:university,国家/地区:country,总分:score})print(f第{page}页爬取完成累计{len(qs_data)}条)time.sleep(1)exceptExceptionase:print(f第{page}页失败{e})continuedfpd.DataFrame(qs_data)df.to_csv(qs2025_rank_raw.csv,indexFalse,encodingutf-8-sig)returndf# 3. 数据清洗 defclean_data(df):# 删除缺失值dfdf.dropna(subset[排名,学校名称,国家/地区,总分])# 清洗排名df[排名]df[排名].str.replace(,).astype(int)# 清洗总分defclean_score(score):try:returnfloat(score)except:returnNonedf[总分]df[总分].apply(clean_score)dfdf.dropna(subset[总分])# 去重dfdf.drop_duplicates(subset[排名],keepfirst)dfdf.reset_index(dropTrue)df.to_csv(qs2025_rank_clean.csv,indexFalse,encodingutf-8-sig)print(数据清洗完成保存为qs2025_rank_clean.csv)returndf# 4. 数据分析与可视化 defanalyze_data(df):# 4.1 TOP50国家分布top50df[df[排名]50]country_counttop50[国家/地区].value_counts()plt.figure(figsize(12,6))country_count.plot(kindbar,colorsteelblue)plt.title(2025 QS TOP50 - 国家/地区分布,fontsize14)plt.xlabel(国家/地区,fontsize12)plt.ylabel(数量,fontsize12)plt.xticks(rotation45)plt.tight_layout()plt.savefig(top50_country_dist.png,dpi300)plt.show()# 4.2 主要国家TOP100占比top100df[df[排名]100]main_countries[United States,United Kingdom,China,Japan,Germany,Canada,Australia]top100_maintop100[top100[国家/地区].isin(main_countries)]country_count_top100top100_main[国家/地区].value_counts()plt.figure(figsize(10,10))plt.pie(country_count_top100.values,labelscountry_count_top100.index,autopct%1.1f%%,startangle90,colorsplt.cm.Set3.colors)plt.title(2025 QS TOP100 - 主要国家占比,fontsize14)plt.tight_layout()plt.savefig(top100_country_pie.png,dpi300)plt.show()# 4.3 TOP100总分分布plt.figure(figsize(10,6))plt.hist(top100[总分],bins15,colorlightcoral,edgecolorblack)plt.axvline(top100[总分].mean(),colorred,linestyle--,labelf平均分{top100[总分].mean():.2f})plt.title(2025 QS TOP100 - 总分分布,fontsize14)plt.xlabel(总分,fontsize12)plt.ylabel(数量,fontsize12)plt.legend()plt.tight_layout()plt.savefig(top100_score_dist.png,dpi300)plt.show()# 4.4 中国高校表现china_unisdf[df[国家/地区].str.contains(China,naFalse)]china_top100china_unis[china_unis[排名]100].sort_values(排名)print(中国高校TOP100)print(china_top100[[排名,学校名称,国家/地区,总分]])plt.figure(figsize(10,6))plt.scatter(china_top100[排名],china_top100[总分],colordarkgreen,s80)foridx,rowinchina_top100.iterrows():plt.annotate(row[学校名称],(row[排名],row[总分]),fontsize8,haright)plt.title(2025 QS TOP100 - 中国高校排名vs总分,fontsize14)plt.xlabel(排名,fontsize12)plt.ylabel(总分,fontsize12)plt.tight_layout()plt.savefig(china_unis_scatter.png,dpi300)plt.show()# 主函数 if__name____main__:# 爬取数据若已爬取可注释直接加载raw_dfcrawl_qs_rank()# 清洗数据clean_dfclean_data(raw_df)# 分析数据analyze_data(clean_df)七、分析结果解读示例TOP50分布美国依旧占据主导地位约20所英国次之约8所中国内地有5所左右进入TOP50TOP100占比美国占比超40%英国约15%中国含港澳台约8%总分分布TOP100高校总分集中在70-95分区间前10名总分均超90分分数差距随排名提升逐渐缩小中国高校清华大学、北京大学稳居中国高校榜首进入TOP20中国香港的香港大学、香港科技大学也表现亮眼跻身TOP50。八、拓展方向爬取历年QS排名数据分析高校排名变化趋势加入更多维度分析如学科排名、师生比、国际生比例等结合地理信息绘制全球高校分布热力图用机器学习预测高校排名变化如基于总分、学科表现等特征。九、注意事项爬取数据时需遵守网站robots.txt协议避免高频请求QS官网页面结构可能更新需及时调整爬虫的CSS选择器数据仅供学习使用请勿用于商业用途。总结本文通过Python完成了QS世界大学排名的全流程分析从数据爬取到可视化覆盖了数据分析的核心环节。掌握这套思路后你可以举一反三分析其他排名如泰晤士、U.S. News或行业数据。希望本文能帮助你提升Python数据分析能力也为留学选校、高校研究提供参考