# Python怎么爬取中國大學排名并且保存到excel中
## 前言
在當今信息爆炸的時代,數據獲取和處理能力已成為一項重要技能。教育領域的數據,特別是大學排名數據,對于學生擇校、學術研究等都具有重要參考價值。本文將詳細介紹如何使用Python爬取中國大學排名數據,并將結果保存到Excel文件中。
## 一、準備工作
### 1.1 所需工具和庫
在開始之前,我們需要準備以下Python庫:
- `requests`:用于發送HTTP請求
- `BeautifulSoup`:用于解析HTML文檔
- `pandas`:用于數據處理和Excel導出
- `openpyxl`:pandas導出Excel所需的引擎
可以通過以下命令安裝這些庫:
```python
pip install requests beautifulsoup4 pandas openpyxl
我們以”軟科中國大學排名”為例(假設目標網址為:https://www.shanghairanking.cn/rankings/bcur/2023)。在編寫爬蟲前,我們需要:
使用瀏覽器開發者工具(F12)可以查看網頁的HTML結構。
首先,我們需要獲取網頁內容:
import requests
from bs4 import BeautifulSoup
url = "https://www.shanghairanking.cn/rankings/bcur/2023"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8' # 確保中文正常顯示
使用BeautifulSoup解析獲取的HTML:
soup = BeautifulSoup(response.text, 'html.parser')
通過分析網頁結構,找到包含排名數據的表格:
rank_table = soup.find('table', {'class': 'rk-table'}) # 假設表格類名為rk-table
遍歷表格行,提取所需數據:
universities = []
for row in rank_table.find_all('tr')[1:]: # 跳過表頭
cols = row.find_all('td')
if len(cols) > 1: # 確保有數據
rank = cols[0].text.strip()
name = cols[1].text.strip()
score = cols[2].text.strip()
universities.append({
'排名': rank,
'學校名稱': name,
'總分': score
})
將提取的數據轉換為DataFrame:
import pandas as pd
df = pd.DataFrame(universities)
對數據進行必要的清洗:
# 去除空值
df = df.dropna()
# 重置索引
df = df.reset_index(drop=True)
將數據保存為Excel文件:
df.to_excel('中國大學排名.xlsx', index=False, engine='openpyxl')
import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_university_ranking():
url = "https://www.shanghairanking.cn/rankings/bcur/2023"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
# 發送請求
response = requests.get(url, headers=headers)
response.raise_for_status() # 檢查請求是否成功
response.encoding = 'utf-8'
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
rank_table = soup.find('table', {'class': 'rk-table'})
# 提取數據
universities = []
for row in rank_table.find_all('tr')[1:]:
cols = row.find_all('td')
if len(cols) > 1:
rank = cols[0].text.strip()
name = cols[1].text.strip()
score = cols[2].text.strip()
universities.append({
'排名': rank,
'學校名稱': name,
'總分': score
})
# 轉換為DataFrame
df = pd.DataFrame(universities)
df = df.dropna()
df = df.reset_index(drop=True)
# 保存到Excel
df.to_excel('中國大學排名.xlsx', index=False, engine='openpyxl')
print("數據已成功保存到'中國大學排名.xlsx'")
except Exception as e:
print(f"發生錯誤: {e}")
if __name__ == "__main__":
get_university_ranking()
import time
import random
# 在請求之間添加隨機延遲
time.sleep(random.uniform(1, 3))
完善異常處理機制:
try:
response = requests.get(url, headers=headers, timeout=10)
except requests.exceptions.RequestException as e:
print(f"請求失敗: {e}")
return None
確保數據的完整性和準確性:
# 檢查數據是否完整
if df.isnull().values.any():
print("警告: 數據中存在空值")
如果需要爬取多頁數據:
base_url = "https://www.shanghairanking.cn/rankings/bcur/2023?page={}"
for page in range(1, 6): # 假設爬取前5頁
url = base_url.format(page)
# 發送請求和解析數據的代碼...
使用schedule庫實現定時爬?。?/p>
import schedule
import time
def job():
print("開始執行爬取任務...")
get_university_ranking()
# 每天上午10點執行
schedule.every().day.at("10:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
使用matplotlib進行簡單的數據可視化:
import matplotlib.pyplot as plt
# 假設我們想展示前20名大學的分數
top20 = df.head(20)
plt.figure(figsize=(12, 8))
plt.barh(top20['學校名稱'], top20['總分'].astype(float), color='skyblue')
plt.xlabel('總分')
plt.title('中國大學排名前20名')
plt.gca().invert_yaxis() # 反轉y軸,使排名第一的在頂部
plt.tight_layout()
plt.savefig('大學排名可視化.png')
plt.show()
A: 這可能是因為網站檢測到了爬蟲。嘗試: - 更換User-Agent - 使用代理IP - 增加請求間隔時間
A: 可以嘗試:
- 指定Excel引擎:engine='openpyxl'
- 調整列寬:使用pandas的ExcelWriter
with pd.ExcelWriter('中國大學排名.xlsx', engine='openpyxl') as writer:
df.to_excel(writer, index=False)
worksheet = writer.sheets['Sheet1']
worksheet.column_dimensions['A'].width = 15 # 調整A列寬度
A: 如果數據是通過JavaScript動態加載的,可以考慮: - 使用Selenium - 分析網站API接口
本文詳細介紹了使用Python爬取中國大學排名并保存到Excel的完整流程,包括:
通過這個案例,你不僅可以掌握基本的網絡爬蟲技術,還能學會如何處理和存儲獲取的數據。這些技能可以應用于各種數據采集場景,為你的學習和研究提供有力支持。
希望這篇文章能幫助你成功爬取中國大學排名數據!如果有任何問題,歡迎在評論區留言討論。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。