开发者

Python: urllib2 handle multiple openers

开发者 https://www.devze.com 2023-01-31 23:55 出处:网络
I have to keep 2 urllib2 openers, one for direct requests and the second to make requests via proxy server and I\'ve to rebuild opener switch between requests.

I have to keep 2 urllib2 openers, one for direct requests and the second to make requests via proxy server and I've to rebuild opener switch between requests.

How to keep con开发者_StackOverflow中文版text openers for example direct and proxy separately?


I suspect your confusion stems from using install_opener and urllib2.urlopen. Instead, just call build_opener twice and store the results in separate objects. Then you can use the appropriate opener when needed.

Example:

import urllib2
direct = urllib2.build_opener()
proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxied = urllib2.build_opener(proxy_handler)


direct.open('http://stackoverflow.com') # opens directly
proxied.open('http://stackoverflow.com') # opens through proxy
0

精彩评论

暂无评论...
验证码 换一张
取 消