bs4 定向爬取中国大学排名

#中国大学排名定向爬虫
#步骤一:从网络上获取大学排名网页内容
#步骤二:提取网页内容中信息到合适的数据结构
#步骤三:利用数据结构展示并输出结果

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值