# 怎么用Python爬取中國大學排名網站排名信息
## 前言
在當今信息時代,教育數據的獲取和分析變得越來越重要。中國大學排名是學生、家長和教育工作者關注的重要參考指標。本文將詳細介紹如何使用Python爬取中國大學排名網站的排名信息,包括數據采集、解析、存儲等完整流程。
## 一、準備工作
### 1.1 工具準備
- Python 3.6+
- Requests庫(發送HTTP請求)
- BeautifulSoup4或lxml(HTML解析)
- Pandas(數據處理)
- 開發工具:PyCharm/VSCode/Jupyter Notebook
### 1.2 目標網站分析
以"軟科中國大學排名"為例(實際使用時請遵守網站robots.txt規定):
https://www.shanghairanking.cn/rankings/bcur/2023
### 1.3 安裝依賴庫
```bash
pip install requests beautifulsoup4 pandas
import requests
url = "https://www.shanghairanking.cn/rankings/bcur/2023"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36..."
}
response = requests.get(url, headers=headers)
print(response.status_code) # 檢查請求狀態
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
通過瀏覽器開發者工具(F12)檢查元素:
- 排名表格通常位于<table>
或<div>
標簽中
- 每所學校信息可能包含在<tr>
或<li>
標簽中
universities = []
table = soup.find('table', {'class': 'rk-table'}) # 根據實際class調整
for row in table.find_all('tr')[1:]: # 跳過表頭
cols = row.find_all('td')
if len(cols) > 3:
rank = cols[0].text.strip()
name = cols[1].text.strip()
score = cols[2].text.strip()
universities.append({
'排名': rank,
'學校名稱': name,
'總分': score
})
base_url = "https://example.com/rankings?page={}"
for page in range(1, 6): # 假設有5頁
url = base_url.format(page)
response = requests.get(url, headers=headers)
# 解析邏輯...
import pandas as pd
df = pd.DataFrame(universities)
df.to_csv('university_ranking.csv', index=False, encoding='utf_8_sig')
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='123456', database='rankings')
cursor = conn.cursor()
create_table = """
CREATE TABLE IF NOT EXISTS universities (
id INT AUTO_INCREMENT PRIMARY KEY,
rank INT,
name VARCHAR(100),
score FLOAT
)
"""
cursor.execute(create_table)
for uni in universities:
insert_sql = f"INSERT INTO universities (rank, name, score) VALUES ({uni['排名']}, '{uni['學校名稱']}', {uni['總分']})"
cursor.execute(insert_sql)
conn.commit()
conn.close()
當數據通過AJAX加載時,可能需要:
import json
ajax_url = "https://example.com/api/rankings"
params = {"year": 2023, "type": "main"}
response = requests.get(ajax_url, params=params)
data = json.loads(response.text)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)
driver.get("https://example.com/dynamic-page")
html = driver.page_source
# 后續解析...
driver.quit()
from fake_useragent import UserAgent
ua = UserAgent()
headers = {'User-Agent': ua.random}
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
requests.get(url, proxies=proxies)
import time
time.sleep(random.uniform(1, 3))
import requests
from bs4 import BeautifulSoup
import pandas as pd
import random
import time
def get_rankings(year=2023):
url = f"https://www.shanghairanking.cn/rankings/bcur/{year}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)..."
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
universities = []
table = soup.find('table', {'class': 'rk-table'})
for row in table.find_all('tr')[1:]:
cols = row.find_all('td')
if len(cols) > 3:
universities.append({
'年份': year,
'排名': cols[0].text.strip(),
'學校代碼': cols[1].text.strip(),
'學校名稱': cols[2].text.strip(),
'省份': cols[3].text.strip(),
'總分': cols[4].text.strip()
})
df = pd.DataFrame(universities)
df.to_csv(f'university_ranking_{year}.csv', index=False, encoding='utf_8_sig')
print(f"成功獲取{year}年排名數據!")
except Exception as e:
print(f"獲取數據失敗: {e}")
if __name__ == '__main__':
for year in range(2019, 2024):
get_rankings(year)
time.sleep(random.uniform(2, 5))
本文詳細介紹了使用Python爬取大學排名數據的完整流程。實際應用中,請根據目標網站的具體結構調整代碼,并始終遵守網絡爬蟲道德規范。通過掌握這些技術,你可以輕松獲取各種公開教育數據,為學習和研究提供數據支持。
注意:本文示例代碼僅供參考,實際使用時請替換為目標網站的真實URL和正確的HTML元素選擇器。部分網站可能有反爬機制,建議在合法合規的前提下進行數據采集。 “`
這篇文章共計約1900字,包含了從基礎到進階的完整爬蟲實現流程,采用Markdown格式編寫,可以直接用于技術博客或文檔分享。實際應用時請確保遵守相關網站的使用條款。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。