读取状态代码

属性 status_code 包含响应的状态代码

good_req = requests.get('https://api.github.com/events')
code_200 = good_req.status_code

notfound_req = requests.get('https://api.github.com/not_found')
code_404 = notfound_req.status_code

requests.codes.__dict__ 将提供可用的 http 状态代码列表。

用户 raise_for_status 可以检查 status_code 是 4xx 还是 5xx,并在这种情况下引发相应的异常。

good_req = requests.get('https://api.github.com/events')
good_req.raise_for_status()
# is a 200 status code so nothing happens

notfound_req = requests.get('https://api.github.com/not_found')
notfound_req.raise_for_status()
# raises requests.exceptions.HTTPError: 404 Client Error