Changing user agent on urllib2.urlopen

后端 未结 9 2281
感动是毒
感动是毒 2020-11-22 13:59

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

9条回答
  •  广开言路
    2020-11-22 14:59

    All these should work in theory, but (with Python 2.7.2 on Windows at least) any time you send a custom User-agent header, urllib2 doesn't send that header. If you don't try to send a User-agent header, it sends the default Python / urllib2

    None of these methods seem to work for adding User-agent but they work for other headers:

    opener = urllib2.build_opener(proxy)
    opener.addheaders = {'User-agent':'Custom user agent'}
    urllib2.install_opener(opener)
    
    request = urllib2.Request(url, headers={'User-agent':'Custom user agent'})
    
    request.headers['User-agent'] = 'Custom user agent'
    
    request.add_header('User-agent', 'Custom user agent')
    

提交回复
热议问题