Python-爬虫-实例中国最好大学排名爬虫

程序的结构设计
第一步:从网络上获取大学排名网页内容
第二步:提取网页内容中信息到合适的数据结构
第三步:利用数据结构展示并输出结果

import requests
from bs4 import BeautifulSoup
import bs4


def getHTMLText(url):  # 返回html页面内容
    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):  # 将html页面内容返回到list列表中
    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):  # 将列表中内容打印出来
    print("{:^10}\t{:6}\t{:^10}".format("排名", "学校名称", "总分"))
    for i in range(num):
        u = ulist[i]
        print("{:^10}\t{:6}\t{:^10}".format(u[0], u[1], u[2]))


if __name__ == "__main__":
    uinfo = []
    url = "http://zuihaodaxue.cn/zuihaodaxuepaiming2019.html"
    html = getHTMLText(url)
    fillUnivList(uinfo, html)
    printUnivList(uinfo, 5)  # 5 univ

import requests
from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):  # 返回html页面内容
    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):  # 将html页面内容返回到list列表中
    soup = BeautifulSoup(html, "html.parser")
    for tr in soup.find('tbody').children:  # 解析html代码中tbody标签所在的位置
        if isinstance(tr, bs4.element.Tag):  # 过滤掉非标签类型数据
            tds = tr('td')
            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)))


if __name__ == "__main__":
    uinfo = []
    url = "http://zuihaodaxue.cn/zuihaodaxuepaiming2019.html"
    html = getHTMLText(url)
    fillUnivList(uinfo, html)
    printUnivList(uinfo, 20)  # 5 univ

你可能感兴趣的:(Python)