当前位置:首页 > 技术 > 正文内容

Python数据爬取与可视化分析

访客 技术 2026年9月11日 10

本文介绍如何通过Python实现大学排名数据的爬取、处理及可视化,并展示曲线绘制的基本方法。

数据爬取与分析

以下代码实现从软科中国最好大学排名网站获取2015年至2019年的排名数据,提取前10名大学的信息并进行可视化展示。同时提供一个查询功能,允许用户输入大学名称和年份以获取对应排名信息。

import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt

def fetch_university_rankings(year):
    base_url = f"https://www.shanghairanking.cn/rankings/bcur/20{year}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    }
    response = requests.get(base_url, headers=headers)
    soup = BeautifulSoup(response.content.decode(), "lxml")
    
    universities = []
    names = soup.find_all("a", class_="name-cn")
    scores = soup.select("#content-box > div.rk-table-box > table > tbody > tr > td:nth-child(5)")
    
    for idx, name in enumerate(names[:10]):
        universities.append([name.text.strip(), scores[idx].text.strip()])
    
    return universities

all_data = []
for year in range(15, 20):
    rankings = fetch_university_rankings(year)
    df = pd.DataFrame(rankings, columns=["学校名称", "总分"])
    all_data.append(df)

# 可视化部分
plt.rcParams['font.sans-serif'] = ['SimHei']
for idx, df in enumerate(all_data):
    labels = df["学校名称"][::-1]
    values = df["总分"].astype(float)[::-1]
    plt.figure(figsize=(20, 8))
    plt.plot(labels, values, label=f"{2015 + idx}年排名")
    plt.grid(True, linestyle="--", alpha=0.5)
    plt.xlabel("学校名称")
    plt.ylabel("总分")
    plt.title(f"{2015 + idx}年软科中国最好大学排名Top10", fontsize=20)
    plt.legend()
    plt.show()

# 查询功能
while True:
    query = input("请输入要查询的大学名称和年份(如:清华大学 2018):").split()
    if len(query) != 2:
        print("输入格式错误,请重新输入!")
        continue
    
    university_name, target_year = query[0], int(query[1])
    year_index = target_year - 2015
    
    if 0 <= year_index < 5:
        names = list(all_data[year_index]["学校名称"])
        if university_name in names:
            rank = names.index(university_name) + 1
            print(f"{university_name}在{target_year}年排名第{rank}")
        else:
            print("未找到该大学的排名记录!")
    else:
        print("未找到该年份的排名记录!")
    
    choice = input("是否继续查询?(y/n):")
    if choice.lower() != 'y':
        break

曲线绘制

以下代码演示在同一坐标系中使用不同颜色和线型绘制三条曲线的方法,以及如何以子图形式展示这些曲线。

import numpy as np
import matplotlib.pyplot as plt

x_values = np.linspace(0, 10, 10000)
curve1 = x_values ** 2
curve2 = np.cos(2 * x_values)
curve3 = curve1 * curve2

# 同一坐标系绘制
plt.figure(figsize=(10, 6))
plt.plot(x_values, curve1, label="y1=x^2", linestyle="--", color="red")
plt.plot(x_values, curve2, label="y2=cos(2x)", linestyle="-.", color="green")
plt.plot(x_values, curve3, label="y3=y1*y2", linestyle="solid", color="blue")
plt.xlabel("X轴")
plt.ylabel("Y轴")
plt.title("同一坐标系下的三条曲线")
plt.legend()
plt.grid(True)
plt.show()

# 子图形式绘制
plt.figure(figsize=(10, 12))
plt.subplot(3, 1, 1)
plt.plot(x_values, curve1, color="red")
plt.title("y1=x^2")

plt.subplot(3, 1, 2)
plt.plot(x_values, curve2, color="green")
plt.title("y2=cos(2x)")

plt.subplot(3, 1, 3)
plt.plot(x_values, curve3, color="blue")
plt.title("y3=y1*y2")
plt.tight_layout()
plt.show()

上述代码展示了如何通过matplotlib库完成曲线绘制任务。

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。