网络请求失败:Python发送HTTP请求时,处理失败响应的方法?

原创 墨蓝 2025-02-06 09:09 107阅读 0赞

在Python中,发送HTTP请求并处理失败响应通常使用requests库。以下是处理失败响应的几种常见方法:

  1. 检查status_code
    发送请求后,可以获取到服务器返回的状态码(HTTP Status Code)。如果状态码不是200(成功),说明请求失败。
  1. response = requests.get('http://example.com', timeout=5)
  2. if response.status_code != 200:
  3. print("Request failed with status code:", response.status_code)
  1. 使用try/except
    当你需要捕获并处理异常时,可以使用try/except块。
  1. response = requests.get('http://example.com', timeout=5)
  2. try:
  3. if response.status_code != 200:
  4. print("Request failed with status code:", response.status_code)
  5. except requests.exceptions.RequestException as e:
  6. print(f"An error occurred: {e}")
  1. 使用异常处理模块(like httpx
    如果你想用第三方库来发送请求,例如HTTPX,你可以直接在try/except块中调用方法。
  1. from httpx import Client
  2. client = Client()
  3. response = client.get('http://example.com', timeout=5)
  4. try:
  5. if response.status_code != 200:
  6. print("Request failed with status code:", response.status_code)
  7. except httpx.RequestError as e:
  8. print(f"An error occurred: {e}")

以上就是在Python中处理HTTP请求失败的几种方法。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,107人围观)

还没有评论,来说两句吧...

相关阅读