Home >Backend Development >Python Tutorial >How to Send a Custom User-Agent Header with Python\'s Requests Library?

How to Send a Custom User-Agent Header with Python\'s Requests Library?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 03:13:12249browse

How to Send a Custom User-Agent Header with Python's Requests Library?

Sending "User-agent" Using Requests Library in Python

The "User-agent" is a standard HTTP header field that identifies the type of web browser (or other user agent) that is making the request. It can be useful for website owners to know what kind of devices are accessing their site.

To send a custom "User-agent" value using the Python Requests library, it is acceptable to specify it as a field in the request headers.

Method with Requests v2.13 and Newer

For Requests versions 2.13 and later, the simplest approach is to create a dictionary and directly specify the headers.

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

Method with Requests v2.12.x and Older

For older versions of Requests (v2.12.x and earlier), it is necessary to preserve the default headers and then add the custom "User-agent" value.

import requests

url = 'SOME URL'

# Get a copy of the default headers that Requests would use.
headers = requests.utils.default_headers()

# Update the headers with your custom ones.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

In either case, the "User-agent" value will be included in the request headers and sent to the remote server.

The above is the detailed content of How to Send a Custom User-Agent Header with Python\'s Requests Library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn