我用以下命令打开urls:
site = urllib2.urlopen('http://google.com')
我想要做的是以同样的方式连接到我在某处得到的代理:
site = urllib2.urlopen('http://google.com', proxies={'http':'127.0.0.1'})
但这也不管用。
我知道urllib2有一个类似代理处理程序的东西,但我不记得那个函数了。
发布于 2009-09-20 02:49:36
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
发布于 2009-09-20 02:34:40
您必须安装ProxyHandler
urllib2.install_opener(
urllib2.build_opener(
urllib2.ProxyHandler({'http': '127.0.0.1'})
)
)
urllib2.urlopen('http://www.google.com')
发布于 2013-11-08 02:03:36
您可以使用环境变量设置代理。
import os
os.environ['http_proxy'] = '127.0.0.1'
os.environ['https_proxy'] = '127.0.0.1'
urllib2
将以这种方式自动添加代理处理程序。您需要为不同的协议单独设置代理,否则会失败(就不通过代理而言),如下所示。
例如:
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
# next line will fail (will not go through the proxy) (https)
urllib2.urlopen('https://www.google.com')
相反,
proxy = urllib2.ProxyHandler({
'http': '127.0.0.1',
'https': '127.0.0.1'
})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
# this way both http and https requests go through the proxy
urllib2.urlopen('http://www.google.com')
urllib2.urlopen('https://www.google.com')
https://stackoverflow.com/questions/1450132
复制相似问题