Python測試函數的方法之一是用:try……except
def gameover(a,b):if a>=10 and b>=10 and abs(a-b)==2:return Trueif (a>=11 and b<11) or (a<11 and b>=11):return Truereturn False try:a=gameover(10,11)print(a) except:print("Error")
?
gameover測試的函數,沒傳參數的a,b,函數結果是True or False
try:試著執行gameover()函數,正常就執行函數
except:否則 打印'Error'
這里用10,11這一對來測試,結果為:
runfile('D:/新建文件夾/chesi.py', wdir='D:/新建文件夾')
True
程序運行正常且結果正確
若不輸入參數,結果應為Error,結果為:
?
打開360搜索20次
用requests()打開360搜索
代碼如下:
from requests import *
try:
??? for i in range(20):
??????? r=get("https://www.so.com/")
??????? r.raise_for_status()
??????? r.encoding='utf-8'
??????? print(r)
??? print(len(r.text))
??? print(len(r.content))
except:
??? print("Error")
結果成功顯示200?
成功
?
?
?
下面有一段html代碼;
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>菜鳥教程(runoob.com)</title>
</head>\n<body>
<h1>我的第一標題</h1>
<p ?id='frist'>我的第一段落。</p>
</body>
</table>
</html>
我們需要做以下要求:
?
我們有以下代碼解決:
from bs4 import BeautifulSoup import re html = BeautifulSoup("<!DOCTYPE html>\n<html>\n<head>\n<meta charset='utf-8'>\n<title>菜鳥教程(runoob.com)</title>\n</head>\n<body>\n<h1>我的第一標題</h1>\n<p id='frist'>我的第一段落。</p>\n</body>\n</table>\n</html>","html.parser") print(html.head,"20") print(html.body) print(html.find_all(id="first")) r=html.text pattern = re.findall(u'[\u1100-\uFFFDh]+?',r) print(pattern)
?