python requests module head

Python Requests Module Head

Python requests module is a powerful tool for making HTTP requests in Python. One of the HTTP request methods is the HEAD method that is used to retrieve the header information of a resource without actually getting the resource itself. In this article, we will explore how to use the requests module to make a HEAD request and retrieve header information.

Using requests.head() method

The most straightforward way to make a HEAD request using the requests module is by using the head() method. This method sends a HEAD request to the specified URL and returns the headers of the response. Here's an example of how to use it:


import requests

response = requests.head('https://www.example.com')
print(response.headers)

The above code sends a HEAD request to "https://www.example.com" and prints the headers of the response.

Retrieving specific headers

Sometimes, we may only be interested in retrieving specific headers from the response. We can retrieve a specific header by accessing it using the dictionary-like interface of the response.headers object. Here's an example:


import requests

response = requests.head('https://www.example.com')
content_type = response.headers['content-type']
print(content_type)

The above code sends a HEAD request to "https://www.example.com" and prints the value of the "content-type" header from the response.

Handling errors

When making HTTP requests, errors can occur for various reasons, such as network errors, server errors, or client errors. The requests module provides an easy way to handle errors by raising exceptions. Here's an example:


import requests

try:
    response = requests.head('https://www.example.com')
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(e)

The above code sends a HEAD request to "https://www.example.com" and raises an HTTPError exception if the response status code is not in the 2xx range. We can catch this exception and handle it appropriately.