我打开与网址:

site = urllib2.urlopen('http://google.com')

和我想要做的是同样的方式与代理连接 我得到的地方告诉我:

site = urllib2.urlopen('http://google.com', proxies={'http':'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')

其他提示

您必须安装一个ProxyHandler

urllib2.install_opener(
    urllib2.build_opener(
        urllib2.ProxyHandler({'http': '127.0.0.1'})
    )
)
urllib2.urlopen('http://www.google.com')

可以使用环境变量设置代理。

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')

要使用默认系统代理(例如,从环境http_support变量),当前请求的工作如下(不将其安装到的urllib2全局):

url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()

除了接受的答案: 我素文字给了我一个错误

File "c:\Python23\lib\urllib2.py", line 580, in proxy_open
    if '@' in host:
TypeError: iterable argument required

的解决方案是添加http://在代理字符串前面:

proxy = urllib2.ProxyHandler({'http': 'http://proxy.xy.z:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

你也可以使用要求,如果我们想使用代理来访问网页。 Python 3中的代码:

>>> import requests
>>> url = 'http://www.google.com'
>>> proxy = '169.50.87.252:80'
>>> requests.get(url, proxies={"http":proxy})
<Response [200]>

一个以上的代理也可以被添加。

>>> proxy1 = '169.50.87.252:80'
>>> proxy2 = '89.34.97.132:8080'
>>> requests.get(url, proxies={"http":proxy1,"http":proxy2})
<Response [200]>

在另外设置代理的命令行会话 打开命令行,你可能要运行脚本

netsh winhttp set proxy YourProxySERVER:yourProxyPORT

在该终端运行脚本。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top