爬虫实训——使用python爬取大学排名并且存入数据库及推荐系统

###数据源全都来自软科大学排名官网-如有冒犯请联系删除

1、主页界面

2、大学排名

成果显示:

使用tkinterpandasExcel中的数据在tkinter界面中显示;

main函数中返回的文件路径和文件名,先将文件路径对应的Excel文件读取后,将数据逐个插入;

3、各专业的大学排名

4、查询系统

 ####注意查询学校的程序必须要将大学排名中2020-2024年的排榜运行完后才能运行!!!!!

我们先点击                                          中国大学排名(主榜)

         !!!!!!!需要将以上五年的2020   2021   2022  2023  2024先运行一遍存入数据库中

        运行完会在创建的自己创建的test目录中生成以下这些表,我们的查询系统以及推荐系统都是从数据库中读取过来的!!!!!

5、推荐系统

1、数据爬取

使用Beautifulsoup爬取网页数据,将数据存放在对应的字典当中组成列表。

将爬取的数据以CSV形式存放在当前文件夹中。

将存好的CSV文件转换成EXCEL格式。

def get_one_page(url):
    try:
        headers = {
            'User-Agent':
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'
        }

        #  https://www.shanghairanking.cn/rankings/bcur/%s
        one_rank_url = url
        # print(url)

        response = requests.get(one_rank_url, headers=headers)
        if response.content is not None:
            content = response.content.decode('utf-8')
            # print(content.encode('gbk', errors='ignore').decode('gbk'))
            return content.encode('gbk', errors='ignore').decode('gbk'), one_rank_url
        else:
            content = ""
            return content.encode('gbk', errors='ignore').decode('gbk'), one_rank_url
            # print(content.encode('gbk', errors='ignore').decode('gbk'))

    except RequestException:
        print('爬取失败')





def extract_university_info(data):
    soup = BeautifulSoup(data, 'html.parser')
    table = soup.find('table', {'data-v-4645600d': "", 'class': 'rk-table'})
    tbody = table.find('tbody', {'data-v-4645600d': ""})
    rows = tbody.find_all('tr')
    university_info = []
    for row in rows:
        test_len = len(row.find_all('td'))
        # print(test_len)
        rank = row.find('div', {'class': 'ranking'}).text.strip()
        univ_name_cn = row.find('a', {'class': 'name-cn'}).text.strip()
        univ_name_en = row.find('a', {'class': 'name-en'}).text.strip()
        location = row.find_all('td')[2].text.strip()
        category = row.find_all('td')[3].text.strip()
        score = row.find_all('td')[4].text.strip()
        if test_len > 5:
            rating = row.find_all('td')[5].text.strip()
        else:
            rating = None

        info = {
            "排名": rank,
            "名称": univ_name_cn,
            "Name (EN)": univ_name_en,
            "位置": location,
            "类型": category,
            "总分": score,
            "评分": rating,
        }

        keys = info.keys()
        dic = {}
        for key in keys:
            # print(info[key])
            if info[key] != None:
                dic.setdefault(key, info[key])

        university_info.append(dic)
        # 打印数据
        keys = list(dic.keys())
        # print(dic)
        values = list(dic.values())
        for i in range(len(keys)):
            print(keys[i], values[i], sep=': ', end=', ')
            i = i + 1
        print()
    return university_info
# 爬取具体的学科专业排名信息
def extract_subject_info(data):
    soup = BeautifulSoup(data, 'html.parser')
    table = soup.find('table', {'data-v-4645600d': "", 'class': 'rk-table'})
    tbody = table.find('tbody', {'data-v-4645600d': ""})
    rows = tbody.find_all('tr')
    subject_info = []
    for row in rows:
        test_len = len(row.find_all('td'))
        # print(test_len)
        rank = row.find('div', {'class': 'ranking'}).text.strip()
        location = row.find_all('td')[2].text.strip()
        flag = 'univ-name univ-link'
        if location == '中国':
            subject_name_cn = row.find('a', {'class': 'name-cn'}).text.strip()
        else:
            subject_name_cn = row.find('span', {'class': 'univ-name univ-link'}).text.strip()
        # univ_name_en = row.find('a', {'class': 'name-en'}).text.strip()
        category = row.find_all('td')[3].text.strip()
        score = row.find_all('td')[4].text.strip()
        if test_len > 5:
            rating = row.find_all('td')[5].text.strip()
        else:
            rating = None

        info = {
            "排名": rank,
            "名称": subject_name_cn,
            "位置": location,
            "总分": category,
            "论文数": score,
            "评分": rating,
        }

        keys = info.keys()
        dic = {}
        for key in keys:
            if info[key] != None:
                dic.setdefault(key, info[key])

        subject_info.append(dic)
        # 打印数据
        keys = list(dic.keys())
        # print(dic)
        values = list(dic.values())
        for i in range(len(keys)):
            print(keys[i], values[i], sep=': ', end=', ')
            i = i + 1
        print()
    return subject_info
# 获取排榜的总页数
def get_total_pages(pagination_html):
    # print(pagination_html)
    soup = BeautifulSoup(pagination_html, 'html.parser')
    pages = soup.find_all('li', class_='ant-pagination-item')
    if pages:
        return int(pages[-1].text)
    return 1
def main(url,year,flag,name):
    # 模拟浏览器
    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys

    service = Service(executable_path=r"C:\Program Files (x86)\Chromebrowser\chromedriver.exe")
    browser = webdriver.Chrome(service=service)
    browser.get(url)
    #获取一页的数据
    html , one_rank_url = get_one_page(url)
    #获取总页数
    total_pages = get_total_pages(html)
    print(total_pages)
    if total_pages > 1:
        for page in range(1, total_pages + 1):
            jump_input_locator = browser.find_element(By.XPATH, '//div[@class="ant-pagination-options-quick-jumper"]/input')
            jump_input = WebDriverWait(browser, 10).until(
                EC.element_to_be_clickable(jump_input_locator)
            )
            jump_input.clear()

            jump_input.send_keys(page)  # 输入页码
            jump_input.send_keys(Keys.RETURN)  # 模拟 Enter 键
            time.sleep(0.1)  # 等待页面加载

            html = browser.page_source  # 获取网页源码
            if flag == 1:
                content = extract_university_info(html)
            else:
                content = extract_subject_info(html)
            filename, fieldnames = write_to_csv(content, name, year, flag)
        time.sleep(1)
        browser.quit()
    else:
        html = browser.page_source
        content = extract_university_info(html)
        filename, fieldnames = write_to_csv(content, name, year, flag)



    file_xlsx = csv_to_xlsx_pd(filename, str(year) + name + '.xlsx', encode='utf-8')
    time.sleep(1)
    create_db(str(year) + name, flag)
    save_db(file_xlsx, fieldnames, str(year) + name, flag)
    return file_xlsx

###这里我们使用selenium模拟浏览器点击换页按

先通过爬虫可以得到总页数

2、数据库的存入

这里我们使用的是DBeaver

以下是数据库存入代码

def create_db(filename, flag):
    conn = Connection(
        host="localhost",
        port=3306,
        user="root",
        database='test',
        password="zhangzijin2004"
    )

    # 创建游标对象
    cur = conn.cursor()
    sql_drop_table = f"DROP TABLE IF EXISTS {filename}"
    cur.execute(sql_drop_table)
    if flag == 1 :
        # 编写创建表的sql
        create_table = f"create table if not exists {filename}(id integer primary key auto_increment,name varchar(100),place varchar(100),type varchar(4),score varchar(40))"
    else:
        create_table = f"create table if not exists {filename}(id integer primary key auto_increment,name varchar(100),place varchar(100),score varchar(40))"
    # 执行sql
    try:
        cur.execute(create_table)
        print("创建表成功")
    except Exception as e:
        print(e)
        print("创建失败")
    finally:
        cur.close()
        conn.close()


def save_db(file_xlsx, fieldnames, filename, flag):
    # 读取Excel文件

    df = pd.read_excel(file_xlsx)

    thing = [[], [], [], [], [], [], []]
    rag = len(fieldnames)
    rag = rag - 1
    print(len(fieldnames))
    for i in range(0,rag):
        for index, row in df.iterrows():
            thing[i].append(row[fieldnames[i]])
        # print(thing[i])

    conn = Connection(
        host="localhost",
        port=3306,
        user="root",
        password="123456"#这里根据你的密码更改,不会的可以去b站上看视频学习数据库,很容易上手
    )

    print(conn.get_server_info())
    # 获取到游标对象
    cursor = conn.cursor()
    # 选择数据库
    conn.select_db("test")
    if flag == 1 :
        for i in range(len(thing[1])):
            cursor.execute(f"insert into {filename} values({i + 1},'{thing[1][i]}','{thing[3][i]}','{thing[4][i]}','{thing[5][i]}')")
    elif flag == 2 :
        for i in range(len(thing[1])):
            cursor.execute(f"insert into {filename} values({i + 1},'{thing[1][i]}','{thing[2][i]}','{thing[3][i]}')")

    conn.commit()
    conn.close()

3、界面以及按钮的设计与显示

root = tk.Tk()
# 只显示最小化按钮和关闭按钮
root.resizable(False,False)
root.minsize(600,750) # 最小尺寸
root.maxsize(600,750) # 最大尺寸
root.title('大学排名查询系统')
root.config(width=300) # 配置参数
root.config(height=300) # 配置参数

def all_university_button(root,href_name):
    button1 = Button(root, text=href_name[0], font=("微软雅黑 -20"), command=University_One)
    print(button1)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root, text=href_name[1], font=("微软雅黑 -20"), command=University_Two)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root, text=href_name[2], font=("微软雅黑 -20"), command=University_Three)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root, text=href_name[3], font=("微软雅黑 -20"), command=University_Four)
    button4.place(x=150, y=275, height=40, width=200)

    button5 = Button(root, text=href_name[4], font=("微软雅黑 -20"), command=University_Five)
    button5.place(x=150, y=350, height=40, width=200)

以下是我们按钮的设计,通过复制加以更改就可以实现最笨的方式显示多个按钮。以下是最复杂的最笨的办法,因为能力有限,就用长篇重复的代码实现了。。。。

def Specialized():#专业排名g
    root.destroy()
    root2 = tk.Tk()
    root2.resizable(False, False)
    root2.minsize(500, 500)  # 最小尺寸
    root2.maxsize(500, 500)  # 最大尺寸
    root2.title('大学排名查询系统')
    root2.config(width=500)  # 配置参数
    root2.config(height=500)  # 配置参数

    button1 = Button(root2,text="理学",font=("微软雅黑 -20"),command=Specialized_One)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root2,text="工学",font=("微软雅黑 -20"),command=Specialized_Two)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root2, text="生命科学", font=("微软雅黑 -20"), command=Specialized_Three)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root2,text="医科",font=("微软雅黑 -20"),command=Specialized_Four)
    button4.place(x=150, y=275, height=40, width=200)

    button5 = Button(root2, text="社会科学", font=("微软雅黑 -20"), command=Specialized_Five)
    button5.place(x=150, y=350, height=40, width=200)

def University_One():#中国大学排名
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)


    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/bcur/%s11' % (str(year))
        name = "中国大学排名"
        path = main(url,year,1,name)
        ranking_text(path,name)
        root.destroy()
        print(url)



    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    print(button1.pack)
    button1.place(x=150, y=300, height=40, width=200)

4、多选按钮的设计

使用Tkinter模块,创建窗口,输入框以及多选按钮,使用check_vars 列表来存放按钮的状态,用tk.IntVar()获取按钮状态,tk.Checkbutton来创建并显示按钮,利用列表生成式将判断为点击的按钮中的标签名称返回给selected_options列表。

废话不多说,直接上代码!!! 

5、整体代码实现 

import pandas as pd
import csv
import requests
from DrissionPage._pages.chromium_page import ChromiumPage
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
import time
from selenium.webdriver.chrome.service import Service  # 新增
from selenium.webdriver.common.by import By
from openpyxl import Workbook
import datetime
from pymysql import Connection
import os
from tkinter import *
import tkinter as tk




def get_one_page(url):
    try:
        headers = {
            'User-Agent':
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'
        }

        #  https://www.shanghairanking.cn/rankings/bcur/%s
        one_rank_url = url
        # print(url)

        response = requests.get(one_rank_url, headers=headers)
        if response.content is not None:
            content = response.content.decode('utf-8')
            # print(content.encode('gbk', errors='ignore').decode('gbk'))
            return content.encode('gbk', errors='ignore').decode('gbk'), one_rank_url
        else:
            content = ""
            return content.encode('gbk', errors='ignore').decode('gbk'), one_rank_url
            # print(content.encode('gbk', errors='ignore').decode('gbk'))

    except RequestException:
        print('爬取失败')





def extract_university_info(data):
    soup = BeautifulSoup(data, 'html.parser')
    table = soup.find('table', {'data-v-4645600d': "", 'class': 'rk-table'})
    tbody = table.find('tbody', {'data-v-4645600d': ""})
    rows = tbody.find_all('tr')
    university_info = []
    for row in rows:
        test_len = len(row.find_all('td'))
        # print(test_len)
        rank = row.find('div', {'class': 'ranking'}).text.strip()
        univ_name_cn = row.find('a', {'class': 'name-cn'}).text.strip()
        univ_name_en = row.find('a', {'class': 'name-en'}).text.strip()
        location = row.find_all('td')[2].text.strip()
        category = row.find_all('td')[3].text.strip()
        score = row.find_all('td')[4].text.strip()
        if test_len > 5:
            rating = row.find_all('td')[5].text.strip()
        else:
            rating = None

        info = {
            "排名": rank,
            "名称": univ_name_cn,
            "Name (EN)": univ_name_en,
            "位置": location,
            "类型": category,
            "总分": score,
            "评分": rating,
        }

        keys = info.keys()
        dic = {}
        for key in keys:
            # print(info[key])
            if info[key] != None:
                dic.setdefault(key, info[key])

        university_info.append(dic)
        # 打印数据
        keys = list(dic.keys())
        # print(dic)
        values = list(dic.values())
        for i in range(len(keys)):
            print(keys[i], values[i], sep=': ', end=', ')
            i = i + 1
        print()
    return university_info
# 爬取具体的学科专业排名信息
def extract_subject_info(data):
    soup = BeautifulSoup(data, 'html.parser')
    table = soup.find('table', {'data-v-4645600d': "", 'class': 'rk-table'})
    tbody = table.find('tbody', {'data-v-4645600d': ""})
    rows = tbody.find_all('tr')
    subject_info = []
    for row in rows:
        test_len = len(row.find_all('td'))
        # print(test_len)
        rank = row.find('div', {'class': 'ranking'}).text.strip()
        location = row.find_all('td')[2].text.strip()
        flag = 'univ-name univ-link'
        if location == '中国':
            subject_name_cn = row.find('a', {'class': 'name-cn'}).text.strip()
        else:
            subject_name_cn = row.find('span', {'class': 'univ-name univ-link'}).text.strip()
        # univ_name_en = row.find('a', {'class': 'name-en'}).text.strip()
        category = row.find_all('td')[3].text.strip()
        score = row.find_all('td')[4].text.strip()
        if test_len > 5:
            rating = row.find_all('td')[5].text.strip()
        else:
            rating = None

        info = {
            "排名": rank,
            "名称": subject_name_cn,
            "位置": location,
            "总分": category,
            "论文数": score,
            "评分": rating,
        }

        keys = info.keys()
        dic = {}
        for key in keys:
            if info[key] != None:
                dic.setdefault(key, info[key])

        subject_info.append(dic)
        # 打印数据
        keys = list(dic.keys())
        # print(dic)
        values = list(dic.values())
        for i in range(len(keys)):
            print(keys[i], values[i], sep=': ', end=', ')
            i = i + 1
        print()
    return subject_info
# 获取排榜的总页数
def get_total_pages(pagination_html):
    # print(pagination_html)
    soup = BeautifulSoup(pagination_html, 'html.parser')
    pages = soup.find_all('li', class_='ant-pagination-item')
    if pages:
        return int(pages[-1].text)
    return 1

# def get_data_from_page(flag, data):
#     if flag == 1:
#         content = extract_university_info(data)
#     else:
#         content = extract_subject_info(data)
#     return content

def write_to_csv(data_list, filename, year, flag):
    # print(data_list)
    filename = str(year) + filename + '.csv'
    # 检查文件是否存在,以决定是否写入表头
    file_exists = False
    try:
        with open(filename, 'r', encoding='utf-8'):
            file_exists = True
    except FileNotFoundError:
        pass

    with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
        if flag == 1:
            fieldnames = ["排名", "名称", "Name (EN)", "位置", "类型", "总分", "评分"]
        else:
            fieldnames = ["排名", "名称", "位置", "总分", "论文数"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        if not file_exists:
            writer.writeheader()  # 写入表头
        for data in data_list:
            writer.writerow(data)
        return filename, fieldnames


def create_db(filename, flag):
    conn = Connection(
        host="localhost",
        port=3306,
        user="root",
        database='test',
        password="zhangzijin2004"
    )

    # 创建游标对象
    cur = conn.cursor()
    sql_drop_table = f"DROP TABLE IF EXISTS {filename}"
    cur.execute(sql_drop_table)
    if flag == 1 :
        # 编写创建表的sql
        create_table = f"create table if not exists {filename}(id integer primary key auto_increment,name varchar(100),place varchar(100),type varchar(4),score varchar(40))"
    else:
        create_table = f"create table if not exists {filename}(id integer primary key auto_increment,name varchar(100),place varchar(100),score varchar(40))"
    # 执行sql
    try:
        cur.execute(create_table)
        print("创建表成功")
    except Exception as e:
        print(e)
        print("创建失败")
    finally:
        cur.close()
        conn.close()


def save_db(file_xlsx, fieldnames, filename, flag):
    # 读取Excel文件

    df = pd.read_excel(file_xlsx)

    thing = [[], [], [], [], [], [], []]
    rag = len(fieldnames)
    rag = rag - 1
    print(len(fieldnames))
    for i in range(0,rag):
        for index, row in df.iterrows():
            thing[i].append(row[fieldnames[i]])
        # print(thing[i])

    conn = Connection(
        host="localhost",
        port=3306,
        user="root",
        password="zhangzijin2004"
    )

    print(conn.get_server_info())
    # 获取到游标对象
    cursor = conn.cursor()
    # 选择数据库
    conn.select_db("test")
    if flag == 1 :
        for i in range(len(thing[1])):
            cursor.execute(f"insert into {filename} values({i + 1},'{thing[1][i]}','{thing[3][i]}','{thing[4][i]}','{thing[5][i]}')")
    elif flag == 2 :
        for i in range(len(thing[1])):
            cursor.execute(f"insert into {filename} values({i + 1},'{thing[1][i]}','{thing[2][i]}','{thing[3][i]}')")

    conn.commit()
    conn.close()


def csv_to_xlsx_pd(sourcePath, savePath, encode='utf-8'):
    """将csv 转为 excel(.xlsx格式)
    如果不需要可以把计时相关代码删除
    Args:
        sourcePath:str 来源文件路径
        savePath:str 保存文件路径,需要包含保存的文件名,文件名需要是 xlsx 格式的
        encode='utf-8' 默认编码,可以改为需要的编码如gbk
    """
    print('开始处理%s' % sourcePath)
    curr_time = datetime.datetime.now()
    print(curr_time)

    f = open(sourcePath, 'r', encoding=encode)
    # 创建一个workbook 设置编码
    workbook = Workbook()
    # 创建一个worksheet
    worksheet = workbook.active
    workbook.title = 'sheet'

    for line in f:
        row = line.split(',')
        worksheet.append(row)
        # if row[0].endswith('00'):    # 每一百行打印一次
        #     print(line, end="")

    workbook.save(savePath)
    print('处理完毕')
    curr_time2 = datetime.datetime.now()
    print(curr_time2 - curr_time)
    return savePath





def main(url,year,flag,name):
    # 模拟浏览器
    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys

    service = Service(executable_path=r"C:\Program Files (x86)\Chromebrowser\chromedriver.exe")
    browser = webdriver.Chrome(service=service)
    browser.get(url)
    #获取一页的数据
    html , one_rank_url = get_one_page(url)
    #获取总页数
    total_pages = get_total_pages(html)
    print(total_pages)
    if total_pages > 1:
        for page in range(1, total_pages + 1):
            jump_input_locator = browser.find_element(By.XPATH, '//div[@class="ant-pagination-options-quick-jumper"]/input')
            jump_input = WebDriverWait(browser, 10).until(
                EC.element_to_be_clickable(jump_input_locator)
            )
            jump_input.clear()

            jump_input.send_keys(page)  # 输入页码
            jump_input.send_keys(Keys.RETURN)  # 模拟 Enter 键
            time.sleep(0.1)  # 等待页面加载

            html = browser.page_source  # 获取网页源码
            if flag == 1:
                content = extract_university_info(html)
            else:
                content = extract_subject_info(html)
            filename, fieldnames = write_to_csv(content, name, year, flag)
        time.sleep(1)
        browser.quit()
    else:
        html = browser.page_source
        content = extract_university_info(html)
        filename, fieldnames = write_to_csv(content, name, year, flag)



    file_xlsx = csv_to_xlsx_pd(filename, str(year) + name + '.xlsx', encode='utf-8')
    time.sleep(1)
    create_db(str(year) + name, flag)
    save_db(file_xlsx, fieldnames, str(year) + name, flag)
    return file_xlsx


root = tk.Tk()
# 只显示最小化按钮和关闭按钮
root.resizable(False,False)
root.minsize(600,750) # 最小尺寸
root.maxsize(600,750) # 最大尺寸
root.title('大学排名查询系统')
root.config(width=300) # 配置参数
root.config(height=300) # 配置参数

def all_university_button(root,href_name):
    button1 = Button(root, text=href_name[0], font=("微软雅黑 -20"), command=University_One)
    print(button1)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root, text=href_name[1], font=("微软雅黑 -20"), command=University_Two)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root, text=href_name[2], font=("微软雅黑 -20"), command=University_Three)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root, text=href_name[3], font=("微软雅黑 -20"), command=University_Four)
    button4.place(x=150, y=275, height=40, width=200)

    button5 = Button(root, text=href_name[4], font=("微软雅黑 -20"), command=University_Five)
    button5.place(x=150, y=350, height=40, width=200)







def get_all_ranking(level, year):
    url = f"https://www.shanghairanking.cn/rankings/{level}/{str(year)}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0"}
    res = requests.get(url, headers=headers)
    soup = BeautifulSoup(res.content, "html.parser")  # 整个页面的元素
    res = soup.find_all("a", attrs={"class": "rank-type-item"})
    href = [i['href'] for i in res]
    href_name = [i.get_text() for i in [j.find("span") for j in res]]
    # print(href)
    # print(href_name)
    return href[:5], href_name[:5]


import tkinter as tk
from tkinter import ttk, Text, Scrollbar, Button, font
import pandas as pd

def ranking_text(route,name):
    def populate_treeview(tree, df):
        # 清空Treeview
        for i in tree.get_children():
            tree.delete(i)

            # 设置列
        for col in df.columns:
            tree.heading(col, text=col)
            # 设置列宽
            tree.column(col, width=100, anchor='center')

            # 插入数据
        for index, row in df.iterrows():
            tree.insert('', 'end', values=row.tolist())


    def read_excel_file(file_path):
        df = pd.read_excel(file_path)
        return df

    # 创建Tkinter窗口
    root = tk.Tk()
    root.title(name)

    # 创建Treeview组件
    tree = ttk.Treeview(root, show='headings')  # 初始时不设置列,稍后在函数中设置
    tree.pack(fill='both', expand=True)

    # 假设你有一个Excel文件路径
    excel_file_path = route  # 替换为你的Excel文件路径

    # 读取Excel文件到DataFrame
    df = read_excel_file(excel_file_path)

    # 设置Treeview的列
    tree['columns'] = df.columns.tolist()

    # 填充Treeview
    populate_treeview(tree, df)






def University():#大学排名
    root.destroy()
    root1 = tk.Tk()
    root1.resizable(False, False)
    root1.minsize(500, 500)  # 最小尺寸
    root1.maxsize(500, 500)  # 最大尺寸
    root1.title('大学排名查询系统')
    root1.config(width=500)  # 配置参数
    root1.config(height=500)  # 配置参数
    href,href_name = get_all_ranking('bcur',2023)
    print(href_name)
    all_university_button(root1,href_name)

def Search():
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入学校:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')
    print(Content)
    entryContent = Entry((root), textvariable=Content)
    # print(entryContent)
    entryContent.place(x=250, y=250, height=40, width=200)

    def Url():
        input_text = entryContent.get()
        # 打印文本
        print("输入的值是:", input_text)
        import pymysql

        word = input_text
        wrod_list = []
        word_rank = []
        word_score = []

        # 数据库连接参数
        db = pymysql.connect(host="localhost",
                             port=3306,
                             user="root",
                             password="zhangzijin2004",  # 数据库密码
                             db='test',  # 数据库名
                             charset='utf8mb4',  # 字符编码
                             cursorclass=pymysql.cursors.DictCursor)  # 使用字典游标,使得结果集更易于使用

        try:
            # idex = 0
            for i in range(2020, 2025):
                flag = 1
                print(f"{i}中国大学排名")
                with db.cursor() as cursor:
                    # 执行SQL查询
                    sql = f"SELECT * FROM {i}中国大学排名"
                    cursor.execute(sql)

                    # 获取所有记录列表
                    results = cursor.fetchall()
                    for row in results:
                        # 打印每一行数据(row是一个字典)
                        # print(row['name'])
                        if row['name'] == word:
                            flag = 0
                            wrod_list.append(row)
                    print(wrod_list)
                    print(f"{i}中国大学排名")
                if flag == 1:
                    wrod_list.append('')

            # wrod_list.pop()
            for i in wrod_list:
                if i == '':
                    word_rank.append(0)
                    word_score.append('未知')
                else:
                    word_rank.append(i['id'])
                    word_score.append(i['score'])
                    # idex = idex + 1
                print(word_rank)


        finally:
            # 关闭数据库连接
            db.close()

        import matplotlib.pyplot as plt
        # 数据
        x_data = ["2020", "2021", "2022", "2023", "2024"]
        y_data = word_rank  # 价格数据
        plt.rcParams['font.family'] = 'SimHei'
        # 创建画布和坐标轴
        fig, ax = plt.subplots()
        # 绘制折线图
        ax.plot(x_data, y_data, marker='o')  # marker='o' 表示在数据点上添加圆圈标记
        plt.gca().invert_yaxis()
        # 设置图表标题和坐标轴标签
        ax.set_title(f"{input_text}近五年排名情况")
        ax.set_xlabel("年份")
        ax.set_ylabel("排名")

        # 显示图表
        plt.show()


    button1 = Button(root, text="查询", font=("微软雅黑 -20"), command=Url)

    button1.place(x=150, y=300, height=40, width=200)

def Recommend():
    # 销毁任何之前存在的Toplevel窗口(如果有的话)
    for widget in root.winfo_children():
        if isinstance(widget, tk.Toplevel):
            widget.destroy()

            # 创建新的Toplevel窗口
    toplevel = tk.Toplevel(root)
    toplevel.title("大学推荐")
    toplevel.minsize(600, 600)
    toplevel.maxsize(600,600)

    label = Label(toplevel, text="请输入地区:", font=("微软雅黑 -20"))
    label.place(x=60, y=200, height=40, width=200)
    # 创建输入框
    entry = tk.Entry(toplevel)
    entry.pack(pady=10)
    entry.place(x=250, y=200, height=40, width=200)

    # 创建变量来存储Checkbutton的状态
    check_vars = []
    options = ["综合", "理工", "师范", "农业"]

    # 创建一个Frame来放置Checkbutton,使其更整齐
    checkbutton_frame = tk.Frame(toplevel)
    checkbutton_frame.pack(pady=10)
    checkbutton_frame.place(x=160,y=280)

    # 创建Checkbutton控件
    for option in options:
        #获取按钮状态
        var = tk.IntVar()
        check_vars.append(var)
        tk.Checkbutton(checkbutton_frame, text=option, variable=var).pack(side=tk.LEFT, anchor="w", padx=5, pady=5)

        # 创建提交按钮

    def on_submit():
        input_text = entry.get()
        selected_options = [options[i] for i, var in enumerate(check_vars) if var.get()]
        print(f"输入的值是: {input_text}")
        print(f"选择的值是:{selected_options}")

        import pymysql

        word = input_text
        wrod_list = []
        word_rank = []
        word_score = []

        # 数据库连接参数
        db = pymysql.connect(host="localhost",
                             port=3306,
                             user="root",
                             password="123456",  # 数据库密码
                             db='test',  # 数据库名
                             charset='utf8mb4',  # 字符编码
                             cursorclass=pymysql.cursors.DictCursor)  # 使用字典游标,使得结果集更易于使用

        try:

            for i in range(2024, 2025):
                flag = 1
                print(f"{i}中国大学排名")
                with db.cursor() as cursor:
                    # 执行SQL查询
                    sql = f"SELECT * FROM {i}中国大学排名"
                    cursor.execute(sql)

                    # 获取所有记录列表
                    results = cursor.fetchall()
                    for row in results:
                        # 打印每一行数据(row是一个字典)
                        # print(row['name'])
                        if row['place'] == word:
                            for i in selected_options:
                                if row['type'] == i:
                                # if row['']
                                    flag = 0
                                    wrod_list.append(row)
                    print(wrod_list)
                    print(f"{i}中国大学排名")
                if flag == 1:
                    wrod_list.append('')

            # wrod_list.pop()
            for i in wrod_list:
                if i == '':
                    word_rank.append(0)
                    word_score.append('未知')
                else:
                    word_rank.append(i['id'])
                    word_score.append(i['name'])

            print(word_rank)
            print(word_score)
        finally:
            # 关闭数据库连接
            db.close()

        import matplotlib.pyplot as plt
        # 数据
        x_data = word_score
        y_data = word_rank  # 价格数据
        plt.rcParams['font.family'] = 'SimHei'
        # 创建画布和坐标轴
        fig, ax = plt.subplots()
        # 绘制折线图
        ax.plot(x_data, y_data, marker='o')  # marker='o' 表示在数据点上添加圆圈标记
        plt.gca().invert_yaxis()
        # 设置图表标题和坐标轴标签
        ax.set_title(f"{input_text}大学推荐")
        ax.set_xlabel("院校")
        ax.set_ylabel("排名")

        # 显示图表
        plt.show()

    submit_button = tk.Button(toplevel, text="提交", command=on_submit)
    submit_button.pack(pady=10)
    submit_button.place(x=190, y=380, height=40, width=200)


def Specialized():#专业排名g
    root.destroy()
    root2 = tk.Tk()
    root2.resizable(False, False)
    root2.minsize(500, 500)  # 最小尺寸
    root2.maxsize(500, 500)  # 最大尺寸
    root2.title('大学排名查询系统')
    root2.config(width=500)  # 配置参数
    root2.config(height=500)  # 配置参数

    button1 = Button(root2,text="理学",font=("微软雅黑 -20"),command=Specialized_One)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root2,text="工学",font=("微软雅黑 -20"),command=Specialized_Two)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root2, text="生命科学", font=("微软雅黑 -20"), command=Specialized_Three)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root2,text="医科",font=("微软雅黑 -20"),command=Specialized_Four)
    button4.place(x=150, y=275, height=40, width=200)

    button5 = Button(root2, text="社会科学", font=("微软雅黑 -20"), command=Specialized_Five)
    button5.place(x=150, y=350, height=40, width=200)

def University_One():#中国大学排名
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)


    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/bcur/%s11' % (str(year))
        name = "中国大学排名"
        path = main(url,year,1,name)
        ranking_text(path,name)
        root.destroy()
        print(url)



    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    print(button1.pack)
    button1.place(x=150, y=300, height=40, width=200)

    # return button1


def University_Two():#中国医科类大学排名
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/bcur/%s21' % (str(year))
        print(url)
        name = "中国医科类大学排名"
        path = main(url, year, 1, name)
        ranking_text(path,name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)


def University_Three():#中国财经类大学排名
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/bcur/%s22' % (str(year))
        print(url)
        name = "中国财经类大学排名"
        path = main(url, year, 1, name)
        ranking_text(path,name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)


def University_Four():#中国语言类大学排名
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/bcur/%s23' % (str(year))
        print(url)
        name = "中国语言类大学排名"
        path = main(url, year, 1, name)
        ranking_text(path,name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def University_Five():#中国政法类大学排名
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/bcur/%s25' % (str(year))
        print(url)
        name = "中国政法类大学排名"
        path = main(url, year, 1, name)
        ranking_text(path,name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_One():#理学
    root3 = tk.Tk()
    root3.resizable(False, False)
    root3.minsize(500, 500)  # 最小尺寸
    root3.maxsize(500, 500)  # 最大尺寸
    root3.title('大学排名查询系统')
    root3.config(width=500)  # 配置参数
    root3.config(height=500)  # 配置参数

    button1 = Button(root3, text="数学", font=("微软雅黑 -20"), command=Specialized_One1)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root3, text="物理学", font=("微软雅黑 -20"), command=Specialized_One2)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root3, text="化学", font=("微软雅黑 -20"), command=Specialized_One3)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root3, text="地球科学", font=("微软雅黑 -20"), command=Specialized_One4)
    button4.place(x=150, y=275, height=40, width=200)

def Specialized_Two():#工学
    root3 = tk.Tk()
    root3.resizable(False, False)
    root3.minsize(500, 500)  # 最小尺寸
    root3.maxsize(500, 500)  # 最大尺寸
    root3.title('大学排名查询系统')
    root3.config(width=500)  # 配置参数
    root3.config(height=500)  # 配置参数

    button1 = Button(root3, text="机械工程", font=("微软雅黑 -20"), command=Specialized_Two1)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root3, text="电力电子工程", font=("微软雅黑 -20"), command=Specialized_Two2)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root3, text="控制科学与工程", font=("微软雅黑 -20"), command=Specialized_Two3)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root3, text="通信工程", font=("微软雅黑 -20"), command=Specialized_Two4)
    button4.place(x=150, y=275, height=40, width=200)

def Specialized_Three():#生命科学
    root3 = tk.Tk()
    root3.resizable(False, False)
    root3.minsize(500, 500)  # 最小尺寸
    root3.maxsize(500, 500)  # 最大尺寸
    root3.title('大学排名查询系统')
    root3.config(width=500)  # 配置参数
    root3.config(height=500)  # 配置参数

    button1 = Button(root3, text="生物学", font=("微软雅黑 -20"), command=Specialized_Three1)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root3, text="基础医学", font=("微软雅黑 -20"), command=Specialized_Three2)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root3, text="农学", font=("微软雅黑 -20"), command=Specialized_Three3)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root3, text="兽医学", font=("微软雅黑 -20"), command=Specialized_Three4)
    button4.place(x=150, y=275, height=40, width=200)


def Specialized_Four():#医科
    root3 = tk.Tk()
    root3.resizable(False, False)
    root3.minsize(500, 500)  # 最小尺寸
    root3.maxsize(500, 500)  # 最大尺寸
    root3.title('大学排名查询系统')
    root3.config(width=500)  # 配置参数
    root3.config(height=500)  # 配置参数

    button1 = Button(root3, text="临床医学", font=("微软雅黑 -20"), command=Specialized_Four1)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root3, text="公共卫生", font=("微软雅黑 -20"), command=Specialized_Four2)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root3, text="口腔医学", font=("微软雅黑 -20"), command=Specialized_Four3)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root3, text="护理学", font=("微软雅黑 -20"), command=Specialized_Four4)
    button4.place(x=150, y=275, height=40, width=200)

def Specialized_Five():#社会科学
    root3 = tk.Tk()
    root3.resizable(False, False)
    root3.minsize(500, 500)  # 最小尺寸
    root3.maxsize(500, 500)  # 最大尺寸
    root3.title('大学排名查询系统')
    root3.config(width=500)  # 配置参数
    root3.config(height=500)  # 配置参数

    button1 = Button(root3, text="经济学", font=("微软雅黑 -20"), command=Specialized_Five1)
    button1.place(x=150, y=50, height=40, width=200)

    button2 = Button(root3, text="统计学", font=("微软雅黑 -20"), command=Specialized_Five2)
    button2.place(x=150, y=125, height=40, width=200)

    button3 = Button(root3, text="法学", font=("微软雅黑 -20"), command=Specialized_Five3)
    button3.place(x=150, y=200, height=40, width=200)

    button4 = Button(root3, text="政治学", font=("微软雅黑 -20"), command=Specialized_Five4)
    button4.place(x=150, y=275, height=40, width=200)
def Specialized_One1():#数学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0101' % (str(year))
        print(url)
        name = "数学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_One2():#物理学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0102' % (str(year))
        print(url)
        name = "物理学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_One3():#化学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0103' % (str(year))
        print(url)
        name = "化学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_One4():#地球科学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0104' % (str(year))
        print(url)
        name = "地球科学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)


def Specialized_Two1():#机械工程
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0201' % (str(year))
        print(url)
        name = "机械工程排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Two2():#电力电子工程
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0202' % (str(year))
        print(url)
        name = "电力电子工程排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Two3():#控制科学与工程
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0205' % (str(year))
        print(url)
        name = "控制科学与工程排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Two4():#通信工程
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0206' % (str(year))
        print(url)
        name = "通信工程排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Three1():#生物学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0301' % (str(year))
        print(url)
        name = "生物学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Three2():#基础医学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0302' % (str(year))
        print(url)
        name = "基础医学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Three3():#农学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0303' % (str(year))
        print(url)
        name = "农学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Three4():#兽医学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0304' % (str(year))
        print(url)
        name = "兽医学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Four1():#临床医学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0401' % (str(year))
        print(url)
        name = "临床医学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Four2():#公共卫生
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0402' % (str(year))
        print(url)
        name = "公共卫生排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Four3():#口腔医学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0403' % (str(year))
        print(url)
        name = "口腔医学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Four4():#护理学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0404' % (str(year))
        print(url)
        name = "护理学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Five1():#经济学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0501' % (str(year))
        print(url)
        name = "经济学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Five2():#统计学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0502' % (str(year))
        print(url)
        name = "统计学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Five3():#法学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0503' % (str(year))
        print(url)
        name = "法学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()

    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)

def Specialized_Five4():#政治学
    root = tk.Tk()
    root.resizable(False, False)
    root.minsize(600, 600)  # 最小尺寸
    root.maxsize(600, 600)  # 最大尺寸
    root.title('大学排名查询系统')
    root.config(width=600)  # 配置参数
    root.config(height=600)  # 配置参数

    label = Label(root, text="请输入年份:", font=("微软雅黑 -20"))
    label.place(x=45, y=250, height=40, width=200)

    Content = StringVar(root, value='')

    entryContent = Entry((root), textvariable=Content)
    entryContent.place(x=225, y=250, height=40, width=200)

    def Url():
        year = eval(entryContent.get())
        url = 'https://www.shanghairanking.cn/rankings/gras/%s/RS0504' % (str(year))
        print(url)
        name = "政治学排名"
        path = main(url, year, 2, name)
        ranking_text(path, name)
        root.destroy()
    button1 = Button(root, text="确定", font=("微软雅黑 -20"), command=Url)
    button1.place(x=150, y=300, height=40, width=200)



button1 =Button(root,text="大学排名",font=("微软雅黑 -40"),command=University)
button1.place(x=200,y=120,height=80,width=180)

button2 =Button(root,text="专业排名",font=("微软雅黑 -40"),command=Specialized)
button2.place(x=200,y=240,height=80,width=180)


button3 =Button(root,text="查询学校",font=("微软雅黑 -40"),command=Search)
button3.place(x=200,y=360,height=80,width=180)

button4 =Button(root,text="推荐院校",font=("微软雅黑 -40"),command=Recommend)
button4.place(x=200,y=480,height=80,width=180)

root.mainloop()

 代码虽然不是完美,仅供大家参考,互相学习,有不足的地方请大家多多指点!!!!

非常感谢大家的浏览,我会定期更新我的实训代码。--本人也是新手小白,如果需要素材可以评论区留言,我看到会回复的。

  • 25
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值