python爬蟲入門---第二篇:獲取2019年中國大學排名


我們需要爬取的網站:最好大學網

 

我們需要爬取的內容即為該網頁中的表格部分:

 

該部分的html關鍵代碼為:

 

 

其中整個表的標簽為<tbody>標簽,每行的標簽為<tr>標簽,每行中的每個單元格的標簽為<td>標簽,而我們所需的內容即為每個單元格中的內容。

因此編寫程序的大概思路就是先找到整個表格的<tbody>標簽,再遍歷<tbody>標簽下的所有<tr>標簽,最后遍歷<tr>標簽下的所有<td>標簽,

我們用二維列表來存儲所有的數據,其中二維列表中的每個列表用於存儲一行中的每個單元格數據,即<tr>標簽下的所有<td>標簽中的所有字符串。

 

代碼如下;

import requests
from bs4 import BeautifulSoup
import bs4

def get_html_text(url):
    '''返回網頁的HTML代碼'''
    try:
        res = requests.get(url, timeout = 6)
        res.raise_for_status()
        res.encoding = res.apparent_encoding
        return res.text
    except:
        return ''

def fill_ulist(ulist, html):
    '''將我們所需的數據寫入一個列表ulist'''

    #解析HTML代碼,並獲得解析后的對象soup
    soup = BeautifulSoup(html, 'html.parser')
    #遍歷得到第一個<tbody>標簽
    tbody = soup.tbody
    #遍歷<tbody>標簽的孩子,即<tbody>下的所有<tr>標簽及字符串
    for tr in tbody.children:
        #排除字符串
        if isinstance(tr, bs4.element.Tag):
            #使用find_all()函數找到tr標簽中的所有<td>標簽
            u = tr.find_all('td')
            #將<td>標簽中的字符串內容寫入列表ulist
            ulist.append([u[0].string, u[1].string, u[2].string, u[3].string])

def display_urank(ulist):
    '''格式化輸出大學排名'''
    tplt = "{:^5}\t{:{ocp}^12}\t{:{ocp}^5}\t{:^5}"
    #方便中文對其顯示,使用中文字寬作為站字符,chr(12288)為中文空格符
    print(tplt.format("排名", "大學名稱", "省市", "總分", ocp = chr(12288)))
    for u in ulist:
        print(tplt.format(u[0], u[1], u[2], u[3], ocp = chr(12288)))

def write_in_file(ulist, file_path):
    '''將大學排名寫入文件'''
    tplt = "{:^5}\t{:{ocp}^12}\t{:{ocp}^5}\t{:^5}\n"
    with open(file_path, 'w') as file_object:
        file_object.write('軟科中國最好大學排名2019版:\n\n')
        file_object.write(tplt.format("排名", "大學名稱", "省市", "總分", ocp = chr(12288)))
        for u in ulist:
            file_object.write(tplt.format(u[0], u[1], u[2], u[3], ocp = chr(12288)))

def main():
    '''主函數'''
    ulist = []
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
    file_path = 'university rankings.txt'
    html = get_html_text(url)
    fill_ulist(ulist, html)
    display_urank(ulist)
    write_in_file(ulist, file_path)

main()

 

打印顯示:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM