Changing user agent on urllib2.urlopen

das picture das · Apr 29, 2009 · Viewed 145.9k times · Source

How can I download a webpage with a user agent other than the default one on urllib2.urlopen?

Answer

Jason Coon picture Jason Coon · Apr 29, 2009

I answered a similar question a couple weeks ago.

There is example code in that question, but basically you can do something like this: (Note the capitalization of User-Agent as of RFC 2616, section 14.43.)

opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.stackoverflow.com')