#中国大学排名定向爬虫
#步骤一:从网络上获取大学排名网页内容
#步骤二:提取网页内容中信息到合适的数据结构
#步骤三:利用数据结构展示并输出结果
import requests
from bs4 import BeautifulSoup
url = 'https://www.shanghairanking.cn/rankings/bcur/202411'
try:
# 发送HTTP GET请求获取网页内容
response = requests.get(url)
response.raise_for_status() # 检查响应状态码是否为200
response.encoding=response.apparent_encoding # 设置网页编码
# print(response.status_code) # 200
html_text = response.text
# html_content = response.content
except requests.HTTPError as e:
print(e)
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html_text, 'html.parser')
#
# # 找到包含大学信息的表格
table = soup.find('table', class_='rk-table')
# # 遍历表格中的每一行(排除表头)
# rows = table.find_all('tr')[0:10]
# print(rows)
rows = table.find_all('tr')[1:]
#
# # 存储结果的列表
result = []
#
# # 遍历每一行,提取排名、大学名称、地址和分数信息
for row in rows:
# # 提取每一列的数据
cols = row.find_all('td')
ranking = cols[0].text.strip() #去除空格
university = cols[1].text.strip().replace('\n', '') # 删除换行符
address = cols[2].text.strip()
score = cols[4].text.strip()
# # 将数据添加到结果列表中
result.append({
'排名': ranking,
'大学名称': university,
'地址': address,
'分数': score,
})
# # 打印结果
for info in result[:20]:
print(info)
bs4 定向爬取中国大学排名
于 2024-05-20 17:16:40 首次发布