Python-更改urllib2.urlopen上的用户代理
发布于 2021-02-02 23:15:45
如何使用除urllib2.urlopen上的默认代理之外的其他用户代理下载网页?
关注者
0
被浏览
87
1 个回答
-
这个问题中有示例代码,但是基本上你可以执行以下操作:(请注意User-Agent,RFC 2616第14.43节的大写形式。)
opener = urllib2.build_opener() opener.addheaders = [('User-Agent', 'Mozilla/5.0')] response = opener.open('http://www.stackoverflow.com')
-
headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request('www.example.com', None, headers) html = urllib2.urlopen(req).read()
或者,更短一些:
req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' }) html = urllib2.urlopen(req).read()