8-1 【Python0025】中国大学排名数据分析与可视化
【题目描述】以软科中国最好大学排名为分析对象,基于requests库和bs4库编写爬虫程序,对2015年至2019年间的中国大学排名数据进行爬取:
(1)按照排名先后顺序输出不同年份的前10位大学信息,并要求对输出结果的排版进行优化;
(2)结合matplotlib库,对2015-2019年间前10位大学的排名信息进行可视化展示。
(3附加)编写一个查询程序,根据从键盘输入的大学名称和年份,输出该大学相应的排名信息。如果所爬取的数据中不包含该大学或该年份信息,则输出相应的提示信息,并让用户选择重新输入还是结束查询;
【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。
点击查看代码
import matplotlib
matplotlib.use('TkAgg')
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
def get_ranking(year):
"""获取指定年份的前10名大学数据"""
url = f'https://www.shanghairanking.cn/rankings/bcur/{year}'
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', class_='rk-table')
if not table:
print(f"{year}年表格数据不存在")
return None
universities = []
for row in table.select('tbody tr'):
cols = row.find_all('td')
if len(cols) < 3:
continue
# 提取排名和名称
rank = cols[0].text.strip()
name = cols[1].find('a').text.strip() if cols[1].find('a') else cols[1].text.strip()
universities.append({"排名": rank, "名称": name})
if len(universities) >= 10:
break
return universities
except requests.exceptions.RequestException as e:
print(f"{year}年数据获取失败: {str(e)}")
return None
def visualize_rankings(data, year):
"""使用表格形式可视化排名数据"""
if not data:
return
# 生成表格数据
table_data = [[d['排名'], d['名称']] for d in data[:10]]
# 创建更大尺寸的图表对象
fig, ax = plt.subplots(figsize=(12, 8), dpi=100) # 增大画布尺寸
ax.axis('off')
# 创建表格样式(设置更大字体)
table = ax.table(
cellText=table_data,
colLabels=[' 排名 ', ' 大学名称 '], # 增加空格使列宽自然增大
loc='center',
cellLoc='center',
colColours=['#f0f0f0', '#f0f0f0'],
cellColours=[['#FFFFFF']*2 for _ in range(len(table_data))],
bbox=[0.1, 0.1, 0.8, 0.8] # 增大表格相对位置
)
# 设置字体和行高
for key, cell in table.get_celld().items():
cell.set_height(0.25) # 增大行高
if key[0] == 0: # 表头行
cell.get_text().set_fontsize(16)
cell.get_text().set_weight('bold')
else:
cell.get_text().set_fontsize(14)
plt.title(f"{year}年中国大学排名TOP10", fontsize=18, y=1.02)
plt.tight_layout()
try:
plt.show()
except Exception as e:
plt.savefig(f'ranking_{year}.png', bbox_inches='tight')
print(f"可视化结果已保存为 ranking_{year}.png")
def query_ranking():
"""大学排名查询程序"""
print("\n大学排名查询系统(支持2015-2019年)")
while True:
try:
name = input("\n请输入大学全称(输入'退出'结束):").strip()
if name.lower() in ['退出', 'exit']:
break
year = input("请输入查询年份(2015-2019):").strip()
if not year.isdigit() or int(year) not in range(2015, 2020):
print("错误:请输入2015-2019之间的有效年份")
continue
# 获取数据
data = get_ranking(int(year))
if not data:
print("当前年份数据暂不可用")
continue
# 模糊查询逻辑
matches = []
for uni in data:
# 使用包含匹配(不区分大小写)
if name.lower() in uni['名称'].lower():
matches.append(uni)
if matches:
print(f"\n找到{len(matches)}条匹配结果:")
for uni in matches:
print(f"→ {year}年 {uni['名称']} 排名:{uni['排名']}")
else:
print(f"\n→ 未找到包含'{name}'的大学")
except Exception as e:
print(f"查询出错: {str(e)}")
print("-" * 40)
if __name__ == "__main__":
# 任务1:获取并展示历年数据
for year in range(2015, 2020):
data = get_ranking(year)
if data:
print(f"\n{year}年中国大学排名TOP10:")
for i, item in enumerate(data[:10], 1):
print(f"{i:2}. {item['名称']}")
visualize_rankings(data, year)
else:
print(f"{year}年数据获取失败")
# 启动查询程序
query_ranking()
浙公网安备 33010602011771号