网络请求失败:Python发送HTTP请求时,处理失败响应的方法?
在Python中,发送HTTP请求并处理失败响应通常使用requests库。以下是处理失败响应的几种常见方法:
- 检查status_code:
发送请求后,可以获取到服务器返回的状态码(HTTP Status Code)。如果状态码不是200(成功),说明请求失败。
response = requests.get('http://example.com', timeout=5)
if response.status_code != 200:
print("Request failed with status code:", response.status_code)
- 使用try/except:
当你需要捕获并处理异常时,可以使用try/except块。
response = requests.get('http://example.com', timeout=5)
try:
if response.status_code != 200:
print("Request failed with status code:", response.status_code)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
- 使用异常处理模块(like
httpx
):
如果你想用第三方库来发送请求,例如HTTPX,你可以直接在try/except块中调用方法。
from httpx import Client
client = Client()
response = client.get('http://example.com', timeout=5)
try:
if response.status_code != 200:
print("Request failed with status code:", response.status_code)
except httpx.RequestError as e:
print(f"An error occurred: {e}")
以上就是在Python中处理HTTP请求失败的几种方法。
还没有评论,来说两句吧...