avatar
fireworks99
keep hungry keep foolish

定向爬虫:中国大学排名

Description

url:http://www.zuihaodaxue.com/

details

Code

import bs4
import requests
from bs4 import BeautifulSoup

def getText(url):
    try:
        kv = { 'user-agent': 'Mozilla/5.0' }
        r = requests.get(url, headers=kv)
        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: # 找到第一个tbody标签,遍历子节点
        if isinstance(tr, bs4.element.Tag): # 去除(非标签类型)字符串类型(标签树中有标签类型、字符串类型)
            tds = tr('td') # find_all
            ulist.append([ tds[0].string, tds[1].string, tds[2].string ])

def printUnivList(ulist, num):
    tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}" # .format前的输入格式不要乱填空格
    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.zuihaodaxue.com/zuihaodaxuepaiming2019.html"
    html = getText(url)
    fillUnivList(uinfo, html)
    printUnivList(uinfo, 20) # 打印前20所

if __name__ == "__main__":
    main()
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy