Answers:
看一下r.status_code
属性:
if r.status_code == 404:
# A 404 was issued.
演示:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
如果要requests
引发错误代码(4xx或5xx)的异常,请致电r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
您还可以在布尔上下文中测试响应对象。如果状态代码不是错误代码(4xx或5xx),则将其视为“ true”:
if r:
# successful response
如果要更明确,请使用if r.ok:
。
.get()
而不是之后再调用函数。