I want to send a value for "User-agent"
while requesting a webpage using Python Requests. I am not sure is if it is okay to send this as a part of the header, as in the code below:
debug = {'verbose': sys.stderr}
user_agent = {'User-agent': 'Mozilla/5.0'}
response = requests.get(url, headers = user_agent, config=debug)
The debug information isn't showing the headers being sent during the request.
Is it acceptable to send this information in the header? If not, how can I send it?
It's more convenient to use a session, this way you don't have to remember to set headers each time:
By default, session also manages cookies for you. In case you want to disable that, see this question.
The
user-agent
should be specified as a field in the header.Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes
User-Agent
.If you're using requests v2.13 and newer
The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:
If you're using requests v2.12.x and older
Older versions of
requests
clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.