Python Requests Library: Adding Headers
If you want to add headers to a Python Requests Library request, it's very simple. Headers are a way to send additional information about the request to the server. There are two main ways to add headers to a request: manually and with a dictionary.
Manually Adding Headers
To manually add headers, you simply need to set them as key-value pairs in the headers parameter of the request. For example:
import requests
url = 'https://www.example.com'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get(url, headers=headers)
In this example, we're adding a User-Agent header to the request. This is useful if the server requires a specific user agent to access the content. You can add as many headers as you need, just separate them with commas.
Headers Dictionary
You can also add headers using a dictionary:
import requests
url = 'https://www.example.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'From': '[email protected]'
}
response = requests.get(url, headers=headers)
In this example, we're adding a User-Agent header and a From header using a dictionary. This is useful if you have many headers to add, as it keeps your code more organized.