Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send a custom header with urllib2 in a HTTP Request?

I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that?

like image 693
Joakim Avatar asked Dec 22 '08 00:12

Joakim


People also ask

How do I use urllib2?

Simple urllib2 scripturlopen('http://python.org/') print "Response:", response # Get the URL. This gets the real URL. print "The URL is: ", response. geturl() # Getting the code print "This gets the code: ", response.

Does request use Urllib?

Finally, requests internally uses urllib3 , but it aims for an easier-to-use API. Great answer, now I have another reason to not use requests, and be more confident when using the new urllib .

What is Urllib request request?

request — Extensible library for opening URLs. Source code: Lib/urllib/request.py. The urllib. request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.


3 Answers

Not quite. Creating a Request object does not actually send the request, and Request objects have no Read() method. (Also: read() is lowercase.) All you need to do is pass the Request as the first argument to urlopen() and that will give you your response.

import urllib2 request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"}) contents = urllib2.urlopen(request).read() 
like image 129
pantsgolem Avatar answered Oct 06 '22 08:10

pantsgolem


I normally use:

import urllib2

request_headers = {
"Accept-Language": "en-US,en;q=0.5",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": "http://thewebsite.com",
"Connection": "keep-alive" 
}

request = urllib2.Request("https://thewebsite.com", headers=request_headers)
response = urllib2.urlopen(request).read()
print(response)
like image 41
Pedro Lobito Avatar answered Oct 06 '22 09:10

Pedro Lobito


Beside the other solutions mentioned already, you could use add_header method.

So the example provided py @pantsgolem will be:

import urllib2
request = urllib2.Request("http://www.google.com")

request.add_header('Accept','text/html')

##Show the header having the key 'Accept'
request.get_header('Accept')

response = urllib2.urlopen(request)
response.read()
like image 28
user1314742 Avatar answered Oct 06 '22 09:10

user1314742