python 中国大学前十排名

在学校时的代码,网站的数据格式变了,跑不了,就改了下。

有意思的是:vue 将 data 存在了 HTMLElement object 上的 _value property 上,页面上看到的 text 发生改变,但是 HTML 里元素值不会发生改变。

image

import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
from pylab import mpl

# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]

r = requests.get('https://www.shanghairanking.cn/rankings/bcur/202011')
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, 'html.parser')
a = soup.find_all('thead')
ths = a[0].tr.contents
line = []
for th in ths[:5]:
    if th.string:
        line.append(th.string.strip())
    if th.text:
        line.append(th.text.strip())
    else:
        rh = th.find('input')
        line.append(rh.attrs.get('value').strip())
line.append(ths[5].find('li').string)
univ = []
a = soup.find('tbody')
for tr in a.children:
    line = []
    tds = tr.contents
    line.append(tds[0].text.strip())
    line.append(tds[1].a.string.strip())
    line.append(tds[2].contents[0].strip())
    line.append(tds[3].contents[0].strip())
    line.append(tds[4].contents[0].strip())
    line.append(tds[5].contents[0].strip())
    univ.append(line)

dimension = 10
name = list(range(1, dimension + 1))

keys = ['综合', '理工']
scores = [[], []]
for i, ls in enumerate(univ[:dimension]):
    scores[0].append(float(ls[4]) if ls[3] == keys[0] else 400)  # ls[4]为总分
    scores[1].append(float(ls[4]) if ls[3] == keys[1] else 400)  # ls[4]为总分

plt.plot(name, scores[0], 'r-.', label=f'{keys[0]}类大学')
plt.plot(name, scores[1], 'b-.', label=f'{keys[1]}类大学')
plt.xticks(name)
plt.yticks(list(range(400, 900, 50)))
plt.xlabel("排名")
plt.ylabel("评分")
plt.legend(keys, ncol=2)
plt.ylim(400, 900)  # 设置y轴值在400-900之间
plt.title('前十名大学得分')
plt.show()

image

posted @ 2023-10-08 00:07  灵火  阅读(31)  评论(0编辑  收藏  举报