用python爬取2021全国大学排行榜

http://www.gaokao.com/e/20210328/606032dc1b634.shtml

import requests
from bs4 import BeautifulSoup
import bs4


def getHTMLText(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        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')
            ulist.append([tds[0].text.strip(), tds[1].text.strip(), tds[2].text.strip()])       #.strip()去除头尾空格、换行


def printUnivList(ulist, num):
    tplt = "{0:^12}\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 = 'http://www.gaokao.com/e/20210328/606032dc1b634.shtml'
    html = getHTMLText(url)
    fillUnivList(uinfo,html)
    printUnivList(uinfo,34)  # 20 univs


main()
上一篇:PostgreSQL数据库介绍PPT


下一篇:使用selenium爬取猫Y电影Top100榜单