乐闻世界logo
搜索文章和话题

How do I catch a specific HTTP error in Python?

1个答案

1

In Python, capturing specific HTTP errors typically involves using the requests library to send HTTP requests and handling exceptions thrown by the library. The requests library raises certain exceptions when a request fails, one of the most common being requests.exceptions.HTTPError, which is raised when the server returns a non-successful status code (such as 404 or 500).

The following are the steps and examples for capturing specific HTTP errors using the requests library:

1. Install the requests library

If the requests library is not yet installed, you can install it using pip:

bash
pip install requests

2. Send a request and capture exceptions

You can use a try-except block to handle specific HTTP errors. Here is an example demonstrating how to capture a 404 error:

python
import requests from requests.exceptions import HTTPError url = 'https://httpbin.org/status/404' # This URL is used to simulate a 404 error try: response = requests.get(url) # We only process successful requests response.raise_for_status() except HTTPError as http_err: if response.status_code == 404: print(f'HTTP error occurred: 404 Not Found - {http_err}') else: print(f'HTTP error occurred: {http_err}') # Other HTTP errors except Exception as err: print(f'Other error occurred: {err}') # Other errors else: print('Success!')

In this example:

  • We first attempt to send a GET request to the specified URL.
  • The raise_for_status() method raises an HTTPError if the response status code indicates an HTTP error.
  • Use an except block to capture HTTPError, then output different error messages based on the status code. For a 404 error, we output a specific 404 error message.
  • There is also a more general except block to capture other possible exceptions, ensuring the program's robustness.

3. Handling additional HTTP errors

If you need to handle more HTTP errors, you can extend the except block to include additional conditional checks, for example:

python
if response.status_code == 404: print('404 Not Found') elif response.status_code == 500: print('500 Server Error') else: print(f'HTTP error occurred: {http_err}')

This approach allows you to handle various HTTP error scenarios as needed.

2024年8月5日 02:09 回复

你的答案