Python爬取中国大学

Python爬取中国前30名大学


最近在学习爬虫,学习任务中有一个爬取中国前30名的大学,按着教程来爬一直有bug,网上的代码没找到一个能用的…自己探索出来一个供大家学习一下(ps:排名30以后的大学是需要抓包才能爬到么?希望有大佬指点一下)

import requests
import pandas as pd
from bs4 import BeautifulSoup
import bs4


# 爬取中国前一百名的大学
# 获取html
def get_html(url):
    headers = {
    
    
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400"}
    try:
        res = requests.get(url, headers=headers, timeout=30)
        res.encoding = 'utf-8'
        return res.text
    except:
        return ""
    
# 解析html
def parser_html(uni, html):
    soup = BeautifulSoup(html, 'html.parser')
    rank = []
    university = []
    score = []
    # 获取各个大学的信息
    for tr in soup.tbody.children:
        if isinstance(tr, bs4.element.Tag):
            td = tr.find_all('td')
            # 用text获取子标签信息
            rank.append(td[0].text.strip())
            university.append(td[1].find('a').string.strip())
            score.append(float(td[4].text.strip()))
    
    uni['排名'] = rank
    uni['大学名称'] = university
    uni['综合得分'] = score

url = 'https://www.shanghairanking.cn/rankings/bcur/2020'
df_uni = pd.DataFrame(columns=['排名', '大学名称', '综合得分'])
html = get_html(url)
parser_html(df_uni, html)
df_uni

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44424296/article/details/114932708