Python中requests.exceptionsHTTPError()异常的常见错误类型
发布时间:2023-12-26 01:02:52
在Python的requests库中,requests.exceptions.HTTPError()异常是一个常见的错误类型,用于表示HTTP请求发生错误。该异常是requests库中requests.Response.raise_for_status()方法抛出的。
HTTPError异常常见的错误类型如下:
1. 400 - Bad Request: 请求无效,服务器无法理解。
示例代码:
import requests
try:
response = requests.get('https://httpbin.org/status/400')
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(e.response.status_code) # 输出400
print(e.response.content) # 输出错误消息
2. 401 - Unauthorized: 请求需要身份验证,但是没有提供有效的凭据。
示例代码:
import requests
try:
response = requests.get('https://httpbin.org/status/401')
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(e.response.status_code) # 输出401
print(e.response.content) # 输出错误消息
3. 403 - Forbidden: 服务器已经理解请求,但是拒绝执行。
示例代码:
import requests
try:
response = requests.get('https://httpbin.org/status/403')
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(e.response.status_code) # 输出403
print(e.response.content) # 输出错误消息
4. 404 - Not Found: 请求的资源不存在。
示例代码:
import requests
try:
response = requests.get('https://httpbin.org/status/404')
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(e.response.status_code) # 输出404
print(e.response.content) # 输出错误消息
5. 500 - Internal Server Error: 服务器内部错误。
示例代码:
import requests
try:
response = requests.get('https://httpbin.org/status/500')
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(e.response.status_code) # 输出500
print(e.response.content) # 输出错误消息
通过捕获HTTPError异常,我们可以根据具体的错误类型进行处理,例如打印错误消息或者进行其他逻辑操作。
