1.用requests库的get()函数访问如下一个必应20次,打印返回状态,text()内容,计算 text()属性和content属性所返回网页内容的长度。
代码如下:
# -*- 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} {1:{3}^10} {2:^10}'.format('排名', '高校', '分数', chr(12288))) for i in range(num): L = list[i] print('{0:^10} {1:{3}^10} {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()
上次的比赛测试代码
测试函数 本文为上一个比赛规则的函数测试 利用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')