工作中,碰到了這樣一個問題:根據用戶ID獲取用戶信息中的某個參數A。而提供的用戶id中,有些通過接口獲取的用戶信息是空的,那就無法拿到這些用戶信息的參數A。
思考1:而當我想逐個把所有的用戶信息中的參數A寫入一個文件時就不好實現了。怎么解決這個問題呢?想到了用try……except……忽略錯誤。
思考2:如果try內部任意一行代碼出現異常,# 直接跳轉至except,執行except下代碼。此方法只要有一個異常,程序就不繼續執行了。當循環中出現異常時,如何跳過循環中的異常繼續執行呢?
思考3:那就是把try 放在每次執行的循環中,出現錯誤時,在except中用 continue語句繼續到下一個循環。當執行無誤時,把參數A寫入到文件中,當有錯誤時,跳轉到except語句。
思路有了,舉個栗子如下:
import json
import requests
import logging
import time
logging.basicConfig(level=logging.DEBUG,filename='xiangmu.log',format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') #設置日志級別
url_token="http://www.xiangmu.com/employee/getTokenByempCode" #獲取用戶信息接口
usertoken=[]
with open('F:/stand emp.txt','r') as f1:
with open('D:/emptoke.txt','r+') as f2:
lin_content = f1.readlines() #獲取所有用戶
lin_num = len(lin_content)
print(lin_num)
for f1_every in lin_content:
f1_every = f1_every.strip() # 去除行尾的換行符
payload = {'userCode': f1_every} #接口的參數
print(payload)
try:
res=requests.get(url=url_token,params=payload)
usertoken.append(res.json()['data']['token'])
token = res.json()['data']['token'] #獲取所需要的參數A
time.sleep(0.1)
f2.write(token + '\n')
except Exception as e:
logging.info('the exception error is %s, other is %s' % (e.args, repr(e)))
continue
f2.close()
f1.close()