1

我正在尝试维护与代理的连接池。我的代码如下所示:

>>> from urllib3 import PoolManager
>>> pool = PoolManager(10)
>>> pool.urlopen('GET', 'http://http-server/index.html',fields=None,headers=None,encode_multipart=False,multipart_boundary=None,proxies={'http': 'http://proxy'})

当我运行它时,它失败了:

> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in   <module>
>   File "urllib3/poolmanager.py", line 117, in urlopen
>     response = conn.urlopen(method, u.request_uri, **kw)
> File "urllib3/connectionpool.py", line 427, in urlopen
>     **response_kw)   
> File "urllib3/response.py", line 195, in from_httplib
>     **response_kw) 
> TypeError: __init__() got an unexpected keyword argument 'proxies'

知道我做错了什么吗?根据 urllib3 文档,关键字 args 被发送到 urlopen,但在这种情况下似乎没有发生。

这是urllib的链接,描述了代理关键字 arg 的用法。

4

1 回答 1

5

您链接到的文档是 Python 的 urllib,它是与 urllib3 不同的库。当您调用 urllib3 的 urlopen 时,它与 urllib 的 urlopen 不同。对困惑感到抱歉。:)

目前,使用带有 urllib3 的代理还没有很好的文档记录。如果您想探索 urllib3 代码,请查看urllib3.poolmanager.ProxyManager.

否则,我建议尝试在 urllib3 之上简化代理功能的请求。请参阅:http ://docs.python-requests.org/en/latest/user/advanced/?highlight=proxy#proxies

你的代码看起来像这样。

>>> import requests
>>> requests.get('http://http-server/index.html', proxies={'http': 'http://proxy'})

如果您仍然喜欢使用 urllib3,那么使用 urllib3ProxyManager将如下所示:

>>> import urllib3
>>> http = urllib3.proxy_from_url('http://myproxy.com/')  # This returns a ProxyManager object which has the same API as other ConnectionPool objects.
>>> r = http.request('GET', 'http://http-server/index.html')

您也可以直接创建自己的 ProxyManager 对象,但我更喜欢使用proxy_from_url快捷方式。

于 2012-09-19T17:55:58.817 回答