In Python, the requests
library allows you to send HTTP requests with ease. To make a HEAD request, you can use the head
function provided by the library. A HEAD request is similar to a GET request, but it doesn't return the body of the request. It is typically used to retrieve the headers from a resource, which can be useful for checking the existence of a resource, its size, or the type without downloading the entire content.
Here's an example of how to make a HEAD request using the requests
library in Python:
import requests
# The URL you want to send a HEAD request to
url = 'http://example.com'
# Perform the HEAD request
response = requests.head(url)
# Check the status code of the response
print(f'Status code: {response.status_code}')
# Print the headers of the response
print(f'Headers: {response.headers}')
In the above code:
- You import the
requests
library. - You define the URL to which you want to send the HEAD request.
- You use
requests.head()
to send the HEAD request to the specified URL. - You print the status code and the headers of the response to the console.
Note that the response.headers
will contain a CaseInsensitiveDict
object, which is a dictionary that allows case-insensitive access to the HTTP response headers.
If you need to include additional headers with your HEAD request, you can pass them in using the headers
parameter like so:
headers = {
'User-Agent': 'My User Agent',
'Accept': 'text/html',
}
response = requests.head(url, headers=headers)
Always remember to handle possible exceptions that could occur when making HTTP requests, such as ConnectionError
, Timeout
, and HTTPError
. To catch these exceptions, you can use a try-except block:
try:
response = requests.head(url)
# Process the response here
except requests.exceptions.RequestException as e:
# Handle the exception
print(f'An error occurred: {e}')
By using the requests
library's head
function as shown above, you can make HEAD requests in Python quickly and efficiently.