一:編寫函數,(函數執行的時間是隨機的)
import randomhtml
login_lis = {
'username':None
}app
def time_record(func):
def inner():
start_time = time.time()
res = func()
end_time = time.time()
print(f'隨機使用了{end_time - start_time}秒')
return res
return innerdom
二:編寫裝飾器,爲函數加上統計時間的功能
def random_time():
b = random.random()
c=b*10
print('隨機開始')
time.sleep(c)
print('隨機結束')
time_record = time_record(random_time)
time_record()ide
三:編寫裝飾器,爲函數加上登陸認證的功能
四:編寫裝飾器,爲多個函數加上認證的功能(用戶的帳號密碼來源於文件),要求登陸成功一次,後續的函數都無需再輸入用戶名和密碼
def login_auth(func):
def wrapper(*args,**kwargs):
if login_lis['username']:
res = func(*args,**kwargs)
return res
username = input('請輸入你的用戶名:').strip()
password = input('請輸入你的密碼:').strip()
with open('zlp.txt', mode='r', encoding='utf8') as f:
for line in f:
u_name, p_word = line.strip('\n').split(':')
if username == u_name and password == p_word:
print('登陸成功')
# global login_lis
login_lis['username'] = u_name
res = func(*args,**kwargs)
return res
else:
print('用戶名或密碼錯誤')
return wrapper函數
@login_auth
def shopping():
print(login_lis)
print('''
1 麻辣燙
2 洋芋串
3 燒烤
4 奧爾良烤雞腿
''')
chioce = input('請選擇商品')url
@login_auth
def shopping_car():
passcode
shopping()htm
五:編寫下載網頁內容的函數,要求功能是:用戶傳入一個url,函數返回下載頁面的結果
import time
import requestsblog
def spider_outer(url):
def spider_inner():
start_time = time.time()
response = requests.get(url)
end_time = time.time()
if response.status_code == 200:
print(response.text)
print(f'爬取所需時間{end_time - start_time}')
return spider_inner
spider_chioce = spider_outer('https://www.cnblogs.com/zhulipeng-1998/p/11844314.html')
spider_chioce()ip