Python爬取大学排名

#爬取2022中国大学排名信息
import bs4
import requests
import re
from bs4 import BeautifulSoup
def getHTMLText(url):
    # 从网络上获取大学排名网页内容
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""
    return ""


def fillUnivList(ulist, html):
    # 提取网页内容中信息到合适的数据结构
    soup = BeautifulSoup(html, 'html.parser')
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):
            tds = tr('td')
            school_id = tds[0]('div')[0].string.strip() #排名
            school_name = tds[1]('a')[0].string.strip()
            school_score = tds[4].string.strip()
            school_info = [school_id, school_name, school_score]
            ulist.append(school_info)

def printUnivList(ulist, num):
    #利用数据结构展示并输出结果
    tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
    print(tplt.format("排名","学校名称","总分", chr(12288)))
    for i in range(num):
        u = ulist[i]
        print(tplt.format(u[0], u[1], u[2], chr(12288)))

def main():
    uinfo = []
    url = 'https://www.shanghairanking.cn/rankings/bcur/2022'
    html = getHTMLText(url)
    fillUnivList(uinfo, html)
    printUnivList(uinfo, 20)

print(main())

以上代码是根据嵩天老师课程讲解写出的代码。

由于课程中给出的URL页面结构发生变动,fillUnivList()函数代码有所变动。

你可能感兴趣的:(python,开发语言)