# coding=utf-8 ''' request+try__異常處理 ''' import requests class HttpRequests: def __init__(self, url, payload=None): self.url = url self.payload = payload def get_or_post(self, method): try: # try裏面寫的是要監控的code if method.upper() == 'GET': r = requests.get(self.url) res_get = r.text return res_get elif method.upper() == 'POST': self.payload = {'user': 'admin', 'pwd': '123456'} r = requests.post(self.url, data=self.payload) res_post = r.text return res_post else: return '請求的方式不存在......' except Exception as e: # 捕捉異常 print('請求失敗,出現的錯誤是%s ' % e) # 錯誤抓起來,而後代碼能夠繼續執行 # try..Exception把異常信息獲取到,而且對異常進行處理 raise e # 把異常拋出,由於異常捕捉到,還要將這個異常跑出來,不拋的話程序將異常視爲正常,程序繼續運行! if __name__ == '__main__': http_res = HttpRequests('http://www.baidu.com') print(http_res.get_or_post(1))