Python请求是否真的连接到http代理?

时间:2017-08-27 06:01:47

标签: python proxy python-requests

当我使用下面的代码时显然是错误的http代理时,requests模块仍然可以从网址获取。怎么可能呢?这是否意味着requests不会使用http代理?如果是这样,它是否有可能不会https代理?我需要确认我的帖子和获取是通过代理完成的。

import requests
url=r'https://stackoverflow.com/questions'
proxies={'http':'http://asdasdasd:80'}


with requests.session() as s:
    resp = s.get(url, proxies=proxies)
    print resp
    print resp.text

1 个答案:

答案 0 :(得分:1)

您正在设置http代理,但发出https请求。改为设置https代理(或另外)。

import requests

proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}

requests.get('https://example.org', proxies=proxies)

http://docs.python-requests.org/en/master/user/advanced/?highlight=proxies#proxies

使用正确类型的代理集运行示例:

>>> import requests
>>> requests.get('https://example.org', proxies={'https': 'http://asdasdasd:80'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 67, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 53, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 437, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='example.org', port=443):
Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.',
NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at
0x7f3b880b9410>: Failed to establish a new connection: [Errno -2] Name or service not
known',)))
>>>