1. 程式人生 > >爬蟲入門,中國大學排名

爬蟲入門,中國大學排名

此爬蟲本人初學所寫,僅能實現較少功能

ps:需要使用到beautifulsoup, requests庫

安裝方法:pip install beautifulsoup4

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[3].string])
    pass

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():
    uninfo =[]
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html'
    html = getHTmLText(url)
    fillUnivList(uninfo, html)
    printUnivList(uninfo, 100)

main()

列印時使用了chr(12288)進行了中文對齊,美觀一些