根据“pyhon 使用requests库及BeautifulSoup库爬取https://www.shanghairanking.cn/rankings/bcur/2024网站前20名高校信息”,现在需要你按照以下要求给出答案,并写出示例代码,语言是python
时间: 2025-01-18 20:04:00 浏览: 54
好的,我来为您介绍如何使用Python的requests库和BeautifulSoup库来爬取上海交通大学世界大学学术排名网站上的前20名高校信息,并提供相应的示例代码。
首先,我们需要导入必要的库:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
```
然后,我们定义一个函数来获取网页内容:
```python
def get_html(url):
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'
return response.text
```
接下来,我们编写一个函数来解析网页并提取所需信息:
```python
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
rankings = []
# 找到包含大学信息的表格
table = soup.find('table', {'id': 'UniversityRankingTable'})
rows = table.find_all('tr')
# 遍历表格行,跳过表头
for row in rows[1:21]: # 获取前20名
cols = row.find_all('td')
rank = cols[0].text.strip()
name = cols[1].text.strip()
score = cols[2].text.strip()
country = cols[3].text.strip()
rankings.append({
'排名': rank,
'学校名称': name,
'总分': score,
'国家/地区': country
})
return rankings
```
最后,我们编写主函数来整合上述步骤:
```python
def main():
url = 'https://www.shanghairanking.cn/rankings/bcur/2024'
html = get_html(url)
rankings = parse_html(html)
# 将结果保存为CSV文件
df = pd.DataFrame(rankings)
df.to_csv('top_20_universities_2024.csv', index=False, encoding='utf-8-sig')
print("爬取完成,结果已保存为top_20_universities_2024.csv")
```
运行主函数:
```python
if __name__ == '__main__':
main()
```
这段代码会爬取上海交通大学世界大学学术排名网站2024年的前20名高校信息,并将结果保存为一个CSV文件。
阅读全文
相关推荐


















