urllib2/urllib 代理设置
urllib2是Python标准库,功能很强大,只是使用起来稍微麻烦一点。在Python 3中,urllib2不再保留,迁移到了urllib模块中。urllib2中通过ProxyHandler来设置使用代理服务器。
proxy_handler = urllib2.ProxyHandler({'http': '121.193.143.249:80'})
opener = urllib2.build_opener(proxy_handler)
r = opener.open('http://httpbin.org/ip')
print(r.read())
也可以用install_opener将配置好的opener安装到全局环境中,这样所有的urllib2.urlopen都会自动使用代理。
urllib2.install_opener(opener)
r = urllib2.urlopen('http://httpbin.org/ip')
print(r.read())
在Python 3中,使用urllib。
proxy_handler = urllib.request.ProxyHandler({'http': 'http://121.193.143.249:80/'})
opener = urllib.request.build_opener(proxy_handler)
r = opener.open('http://httpbin.org/ip')
print(r.read())
requests 代理设置
requests是目前最优秀的HTTP库之一,也是我平时构造http请求时使用最多的库。它的API设计非常人性化,使用起来很容易上手。给requests设置代理很简单,只需要给proxies设置一个形如 {'http': 'x.x.x.x:8080', 'https': 'x.x.x.x:8080'}
的参数即可。其中http和https相互独立。
>>>requests.get('http://httpbin.org/ip', proxies={'http': '121.193.143.249:80'}).json()
>>>{'origin': '121.193.143.249'}
可以直接设置session的proxies属性,省去每次请求都要带上proxies参数的麻烦。
s = requests.session()
s.proxies = {'http': '121.193.143.249:80'}
print(s.get('http://httpbin.org/ip').json())