Financial data analysis (2) Python warm-up: use bs4 to crawl university rankings in a province

Case (1) Python warm-up

Project 3: Crawling the university rankings of a province

Enter the name of a province, crawl data from the "Ranking of the Best Universities in China 2020" developed by Shanghai Jiaotong University (http://www.zuihaodaxue.cn/zuihaodaxuepaiming2020.html), and output the province's university rankings in 2020.
Input: Guangdong
Output:Insert picture description here

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].string, tds[1].string, tds[2].string])


def printUnivList(ulist, num, place):
    tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
    print("{:^10}\t{:^6}\t{:^10}".format("排名", "学校名称", "省市"))
    for i in range(num):
        u = ulist[i]
        if u[2] == place:
            print(tplt.format(u[0], u[1], u[2], chr(12288)))
#            print("{:^10}\t{:^6}\t{:^10}".format(u[0], u[1], u[2]))
        else:
            continue

def main():
    uinfo = []
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
    html = getHTMLText(url)
    fillUnivList(uinfo, html)
    printUnivList(uinfo, 549, "广东")  # 20 univs


main()

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43082153/article/details/108580710