1. 程式人生 > 實用技巧 >application:bs4+requests對網頁資料進行解析

application:bs4+requests對網頁資料進行解析

邏輯過程:

1.通過requests對網頁進行爬取,返回網頁html

2.通過bs4對網頁資料進行解析,返回列表資料

3.格式化輸出資料

函數語言程式設計:

定義獲取html資料函式,判斷響應情況,返回網頁resopense.text

定義解析函式:通過對資料函式返回內容進行解析,返回解析後的資料

定義展示函式:列印輸出函式

定義執行函式:呼叫其他函式進行執行

亮點:

將所有資料解析放入一個列表中,在展示時,通過設定長度遍歷解析資料所在列表,進行控制讀取資料

問題及相關需要注意點:

soup.find('標籤名').children:需要注意這裡是否成功get了網頁text,未成功可能會報錯

soup.標籤.string:當標籤中有多個子標籤時,會返回None,推薦使用soup.標籤.text

https://blog.csdn.net/lin252931/article/details/105403723

python程式碼實現:

由於本地不好使用爬蟲,因此通過open讀取網頁的形式進行爬取

#中國大學排名定向爬蟲
import requests
from bs4 import BeautifulSoup
import bs4
def getHtmltext(url):
    try:
        res=requests.get(url,timeout=30)
        res.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return " "
def open_html(name):
    with open(name,'rb')as f:
        html=f.read()
    
    return html

def fillUnivList(urlist,html):
    #提取資料
    soup=BeautifulSoup(html,'html.parser')
    for tr  in soup.tbody.children:
        #獲取tbody標籤所有子節點tr標籤
        if isinstance(tr,bs4.element.Tag):
            #判斷獲得所有滿足條件的標籤
            
            tds=tr('td')
            
            #快速獲取tr標籤中的所有tds標籤
            urlist.append([tds[0].string,tds[1].text,tds[2].text])
           
#格式化輸出比較常用print函式的formate格式化字串        

def  printUnivlist(urlist,num):
    print("{0}\t{1}\t{2}".format('排名','學校','地區'))
    for i in  range(num):
        u=urlist[i]
        print("{0}\t{1}\t{2}".format(u[0],u[1],u[2]))
   

def main():
    uinfo=[]
    #url='view-source:http://www.shanghairanking.cn/rankings/bcur/2020'
    #html=getHtmltext(url)
    html=open_html('大學排名.html')
    fillUnivList(uinfo,html)
    
    printUnivlist(uinfo,20)#20 univs
main()