How do I add a header to urllib2 opener? How do I add a header to urllib2 opener? python python

How do I add a header to urllib2 opener?


You can add the headers directly to the OpenerDirector object returned by build_opener. From the last example in the urllib2 docs:

OpenerDirector automatically adds a User-Agent header to every Request. To change this:

import urllib2opener = urllib2.build_opener()opener.addheaders = [('User-agent', 'Mozilla/5.0')]opener.open('http://www.example.com/')

Also, remember that a few standard headers (Content-Length, Content-Type and Host) are added when the Request is passed to urlopen() (or OpenerDirector.open()).


headers = {'foo': 'bar',}req = urllib2.Request(url, None, headers)resp = urllib2.urlopen(req)

or

req = urllib2.Request(url)req.add_header('foo', 'bar')resp = urllib2.urlopen(req)