python 學習 輸出排名後50位大學 DAY4
阿新 • • 發佈:2019-01-04
import requests from bs4 import BeautifulSoup import bs4 def getHTMLText(url): 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): soup = BeautifulSoup(html, "html.parser") data = soup.find_all('tr') #print(data) for tr in data: #print(tr) tds = tr('td') #print(tds) if len(tds)==0: continue ulist.append([tds[0].string,tds[1].string,tds[3].string]) #print(ulist) def printUnivList(ulist, num): print("{0:^10}\t{1:{3}^10}\t{2:^10}".format("排名","學校名稱","總分",chr(12288))) for i in range(551,601): u=ulist[i] print("{0:^10}\t{1:{3}^10}\t{2:{3}^9.1f}".format(u[0],u[1],eval(u[2]),chr(12288))) def wtxt(ulist,num): f = open(r"C:\Users\lenovo\Desktop\中國大學排名.txt",'w+') ls = ['排名','學校名稱','總分'] s = "\t\t".join(ls) f.write(s+'\n') for i in range(num): line = ulist[i] line = "\t\t".join(line) f.write(line+'\n') f.close() def main(): uinfo = [] url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html' html = getHTMLText(url) fillUnivList(uinfo, html) printUnivList(uinfo, 50) # 20 univs wtxt(uinfo,50) main()