1. 程式人生 > 實用技巧 >007 Python網路爬蟲與資訊提取 中國大學排名爬蟲

007 Python網路爬蟲與資訊提取 中國大學排名爬蟲

[A] 中國大學排名定向爬蟲例項介紹

  功能描述

    輸入:大學排名URL連結

    輸出:大學排名資訊的螢幕輸出(排名,大學名稱,總分)

    技術路線:request,bs4

    定向爬蟲:僅對輸入URL進行爬取,不拓展爬取

  程式的結構設計:

    步驟1:從網路上獲取大學排名網頁內容

        定義函式:getHTMLText()

    步驟2:提取網頁內容中資訊到合適的額資料結構

        定義函式:fillUnivList()

    步驟3:利用資料結構展示並輸出結果

        定義函式:printUnivList()

[B] 中國大學排名定向爬蟲例項編寫

    定義了三個函式,分別用來 1. 獲取,2. 儲存 和 3. 展示所爬取的結果

import requests
from bs4 import BeautifulSoup
import bs4

# 中國大學排名

# 1. 從url中獲取所需html程式碼並返回
def getHTMLText(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except
: return '' # 2. 從獲取到的html程式碼中解析出所需要的的資料儲存在列表中並返回 def fillUnivList(html): ulist = [] sublist = [] soup = BeautifulSoup(html, 'html.parser') text = soup.tbody for tr in soup.find('tbody').children: tds = tr('td') for item in tds: sublist.append(item.string) ulist.append(sublist) sublist
= [] return ulist # 3. 根據輸入的資訊,按要求打印出相應資料 def printUnivList(ulist, start, end): print('{:^9}{:^12}{:^15}'.format('排名', '學校名稱', '分數')) for i in range(start, end+1): print('{:^10}{:^12}{:^15}'.format(ulist[i][0], ulist[i][1], ulist[i][2])) # 主程式 def main(): url = 'http://www.gaosan.com/gaokao/299262.html' html = getHTMLText(url) uinfor = fillUnivList(html) printUnivList(uinfor, 5, 30) # 執行主程式 main()
View Code

[C]中國大學排名定向爬蟲例項優化