今天遇到一個奇葩問題,
1.r.request.post(url)
2..print r. status_code
居然第一步就報錯了,原因是url不正確,按道理應該可以走到第二步然后輸入404的
import requests try: requests.get("http://not.a.real.url/really_not") except requests.exceptions.ConnectionError as e: pass >>> e ConnectionError(MaxRetryError("HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)",),) >>> e.args (MaxRetryError("HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)",),) >>> e.args[0] MaxRetryError("HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)",) >>> dir(e.args[0]) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'message', 'pool', 'reason', 'url'] >>> e.args[0].reason gaierror(-2, 'Name or service not known') >>> dir(e.args[0].reason) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'errno', 'filename', 'message', 'strerror'] >>> e.args[0].reason.errno -2
這樣就可以異常設置值
try: r = login_session.post(self.url, data=self.data,headers=self.headers) except requests.exceptions.ConnectionError as e: # print e.args[0].reason #[Errno 11004] getaddrinfo failed if e.args[0].reason.errno== 11004: r = 404 final: return r
得到r,即使不是response類型,也能獲取值
getattr(result, 'status_code', result)