关于http:请求库的Python代理错误

Python Proxy Error With Requests Library

我试图通过python中的代理服务器访问Web。我使用的是请求库,我在验证我的代理时遇到问题,因为我使用的代理需要密码。

1
2
3
4
5
proxyDict = {
          'http'  : 'username:[email protected]',
          'https' : 'username:[email protected]'
        }
r = requests.get("http://www.google.com", proxies=proxyDict)

我收到以下错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Traceback (most recent call last):
File"<pyshell#13>", line 1, in <module>
r = requests.get("http://www.google.com", proxies=proxyDict)
File"C:\Python27\lib\site-packages
equests\api.py"
, line 78, in get
:param url: URL for the new :class:`Request` object.
File"C:\Python27\lib\site-packages
equests\api.py"
, line 65, in request
"""Sends a POST request. Returns :class:`Response` object.
File"C:\Python27\lib\site-packages
equests\sessions.py", line 187, in request
def head(self, url, **kwargs):
File"C:\Python27\lib\site-packages
equests\models.py", line 407, in send
"""

File"C:\Python27\lib\site-packages
equests\packages\urllib3\poolmanager.py"
, line     127, in proxy_from_url
File"C:\Python27\lib\site-packages
equests\packages\urllib3\connectionpool.py"
, line    521, in connection_from_url
File"C:\Python27\lib\site-packages
equests\packages\urllib3\connectionpool.py"
, line 497, in get_host
ValueError: invalid literal for int() with base 10: '[email protected]'

我如何解决这个问题?

事先谢谢你的帮助。


您应该从proxyDict中删除嵌入的用户名和密码,并使用auth参数。

1
2
3
4
5
6
7
8
9
10
import requests
from requests.auth import HTTPProxyAuth

proxyDict = {
          'http'  : '77.75.105.165',
          'https' : '77.75.105.165'
        }
auth = HTTPProxyAuth('username', 'mypassword')

r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)


我在Windows上遇到了类似的问题,我发现让requests工作的唯一方法是在启动python之前将代理设置为环境变量。对你来说,这就像这样:

1
2
set HTTP_PROXY=http://77.75.105.165
set HTTPS_PROXY=https://77.75.105.165

您可能还想检查是否需要特定的端口,如果需要,请在URL之后设置它。例如,如果端口为8443,则执行以下操作:

1
2
set HTTP_PROXY=http://77.75.105.165:8443
set HTTPS_PROXY=https://77.75.105.165:8443


您可以为此使用urllib库。

1
2
from urllib import request
request.urlopen("your URL", proxies=urllib.getproxies())