爬取中國大學排名

2020-09-28 10:00:49

下面展示 程式碼

爬取上海交通大學軟科中國大學排名
import requests
from bs4 import BeautifulSoup

if __name__ == "__main__":
    
    destinationPath = "html資訊.txt"
    allUniv = []
    # headers={'User-Agent':'Mozilla/5.0'}


    url= 'http://www.shanghairanking.cn/rankings/bcur/2020'
    # url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
    
    try:
        # r = requests.get(url=url,headers = headers, timeout=30)
        r = requests.get(url=url, timeout=30)
        r.raise_for_status()
        r.encoding = 'utf-8'
        html = r.text
    except:
        html = ""

    # fd = open(destinationPath,"w+") # 注意這裡會報錯: UnicodeEncodeError: 'gbk' codec can't encode character '\xa9' in position 0: illegal multibyte sequence
    fd = open(destinationPath,"w+",encoding='utf-8')
    fd.writelines(html)
    fd.close()
    # print(html) # 注意在vscode下這裡列印不全,故將結果儲存在檔案中
    
    soup = BeautifulSoup(html, "html.parser")
    # fillUnivList(soup)
    # printUnivList(10)


    print("{0:{5}<10}{1:{5}^10}{2:{5}^12}{3:{5}^10}{4:{5}^10}".format("排名","學校名稱","省市","型別","總分",(chr(12288))))
    data = soup.find_all('tr')

    for tr in data: # 每一行,對應每一個學校
 
        ltd = tr.find_all('td')
        if len(ltd)==0:# if len(ltd)<=1:# if len(ltd)==0:
            continue
  

        singleUniv = []
        # UniName = tr.find('a')
        # singleUniv = [UniName.string]
        for td in ltd:
            if td.find("a"):
                UniName = td.find("a").string
                singleUniv.append(UniName)
            elif td.string.strip():
                singleUniv.append(td.string.strip())
        allUniv.append(singleUniv)
        # print(singleUniv)


    # num = len(allUniv)
    num = 30

    for i in range(num):
        u=allUniv[i]
        print("{0:<10}{1:{5}^20}{2:{5}<10}{3:{5}^4}{4:^33}".format(u[0],u[1],u[2],u[3],u[4],(chr(12288))))
    print("{0:{5}<10}{1:{5}^10}{2:{5}^12}{3:{5}^10}{4:{5}^10}".format("排名","學校名稱","省市","型別","總分",(chr(12288))))

執行結果:

在這裡插入圖片描述
網頁展示:
在這裡插入圖片描述
檢視網頁原始碼:
在這裡插入圖片描述
檢視文字檔案中儲存的html資訊:
在這裡插入圖片描述