1.用requests庫的get()函數訪問以下一個必應20次,打印返回狀態,text()內容,計算 text()屬性和content屬性所返回網頁內容的長度。html
代碼以下:python
# -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import bs4 def getedhtml(url, code='utf-8'): kv = {'user-agent': 'Mozilla/5.0'}#網站有反爬蟲措施,須要改變headers,來假裝本身 try: r = requests.get(url, headers=kv, timeout=30) r. raise_for_status() r.encoding = code return r.text except: return '' def returned(html, list, num): count = 0 #對加入列表中的信息進行計數 soup = BeautifulSoup(html, 'html.parser') info = soup.find('tbody', 'hidden_zhpm').children for tr in info: if count >= num: break #若是以及知足所須要的高校數,就能夠退出了 if isinstance(tr, bs4.element.Tag): count += 1 tds = tr.find_all('td') list.append([tds[0].contents[0], tds[1].string, tds[3].string]) def printed(list, num): print('{0:^10}\t{1:{3}^10}\t{2:^10}'.format('排名', '高校', '分數', chr(12288))) for i in range(num): L = list[i] print('{0:^10}\t{1:{3}^10}\t{2:^10}'.format(L[0], L[1], L[2], chr(12288))) def main(): list = [] url = 'http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html' num = int(input('請問要查詢2019前多少名的高校呢:')) html = getedhtml(url) returned(html, list, num) printed(list, num) main()
上次的比賽測試代碼app
測試函數 本文爲上一個比賽規則的函數測試 利用try-except函數測試是否函數錯誤 1 def gameOver(a,b): 2 if (a>=25 and abs(a-b)>=2 )or(b>=25 and abs(a-b)>=2): 3 return True 4 else: 5 return False 6 ai=[] 7 bi=[] 8 try: 9 for a,b in ((25,25),(26,25),(27,26),(29,25)): 10 if gameOver(a,b): 11 ai.append(a) 12 bi.append(b) 13 except: 14 print('Error') 15 print(ai) 16 print(bi) 這裏是先對gameover函數判斷測試 出來的結果是無錯誤(比分都屬於正常比分,其中一隊大於等於25而且領先另外一隊2分獲勝) 1 try: 2 probA,probB=0.5,0.5 3 scoreA,scoreB=0,0 4 serving = "A" 5 if serving == "A": 6 if random() < probA: 7 scoreA += 1 8 else: 9 serving="B" 10 else: 11 if random() < probB: 12 scoreB += 1 13 else: 14 serving="A" 15 print(scoreA) 16 print(scoreB) 17 except: 18 print('Error') 這裏是對修改後的(由於懶得屢次輸入參數)simOneGame(proA,proB)函數進行測試 發現也沒有錯誤的對局比分出現,其結果爲24,26(結果不惟一) 1 try: 2 n,scoreA,scoreB=1,24,26 3 winsA, winsB = 0, 0 4 scoreA_ls=[] 5 scoreB_ls=[] 6 for i in range(n): 7 scoreA_ls.append(scoreA) 8 scoreB_ls.append(scoreB) 9 if scoreA > scoreB: 10 winsA += 1 11 else: 12 winsB += 1 13 print(winsA, winsB,scoreA_ls,scoreB_ls) 14 except: 15 print('Error')