python爬取
以软科中国最好大学排名为分析对象,基于requests库和bs4库编写爬虫程序,对2015年至2019年间的中国大学排名数据进行爬取:
(1)按照排名先后顺序输出不同年份的前10位大学信息,并要求对输出结果的排版进行优化;
(2)结合matplotlib库,对2015-2019年间前10位大学的排名信息进行可视化展示。(2020-2024)15-19官网已更新,找不到了
(3附加)编写一个查询程序,根据从键盘输入的大学名称和年份,输出该大学相应的排名信息。如果所爬取的数据中不包含该大学或该年份信息,则输出相应的提示信息,并让用户选择重新输入还是结束查询;
import requests from bs4 import BeautifulSoup as bs import pandas as pd from matplotlib import pyplot as pltdef get_rank(url):rank = []headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.3"}resp = requests.get(url, headers=headers)if resp.status_code != 200:print(f"Failed to retrieve data from {url}")return ranksoup = bs(resp.content, "lxml")rows = soup.select("#content-box > div.rk-table-box > table > tbody > tr")for row in rows[:10]: # 获取前10个排名university = row.select_one(".name-cn").text.strip()score = row.select("td:nth-child(5)")[0].text.strip()rank.append([university, score])return ranktotal = [] years = range(2020, 2025) for year in years:url = f"https://www.shanghairanking.cn/rankings/bcur/{year}10"print(f"Fetching data from: {url}")title = ['学校名称', '总分']df = pd.DataFrame(get_rank(url), columns=title)total.append(df)# 画图plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签x = list(df["学校名称"])[::-1]y = list(df["总分"])[::-1]plt.figure(figsize=(20, 8), dpi=100)plt.plot(x, y, label="大学排名", marker='o')plt.grid(True, linestyle="--", alpha=0.5)plt.xlabel("大学名称")plt.ylabel("总分")plt.title(f"{year}年软科中国最好大学排名Top10", fontsize=20)plt.legend(loc="best")plt.savefig(f"{year}.png")plt.show()# 查询功能 def query_ranking():while True:info = input("请输入要查询的大学名称和年份(格式:大学名称 年份):")try:university, year = info.split()year = int(year)if year in years:index = year - 2020df = total[index]if university in df["学校名称"].values:rank = df[df["学校名称"] == university].index[0] + 1print(f"{university}在{year}年排名第{rank}")else:print("很抱歉,没有该学校的排名记录!!!")else:print("很抱歉,没有该年份的排名记录!!!")except ValueError:print("输入格式错误,请输入大学名称和年份(格式:大学名称 年份)")select = input("请选择以下选项:\n 1.继续查询\n 2.结束查询\n")if select == '2':breakif __name__ == "__main__":query_ranking()