Python – Changing user agent on urllib2.urlopen

pythonurllib2user-agent

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

Best Answer

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')