Python教程

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

本文主要是介绍用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()
这篇关于用python爬取2021全国大学排行榜的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!