【问题标题】:HTTPS proxies not working with Python's requests moduleHTTPS 代理不适用于 Python 的请求模块
【发布时间】:2014-06-05 10:46:02
【问题描述】:

我对 Python 还是很陌生,我一直在使用他们的 requests 模块来替代 PHP 的 cURL 库。我的代码如下

import requests
import json
import os
import urllib
import math
import sys

def main() :    
   url = 'https://api.com'

   headers = {'Content-Type': 'application/json; charset=utf-8',
              'User-Agent': '(iPhone; iOS 7.0.4; Scale/2.00)'}

   d = {'token': "12345"}

   proxies = {
      "https": "https://27.254.52.99:8080",
   }

   post = json.dumps(d);
   r = requests.post(url, data=post, headers=headers, proxies=proxies)
   print r.json

if __name__ == "__main__":
    main()

但是,我收到以下错误:

File "test.py", line 42, in test
r = requests.post(url, data=post, headers=headers, proxies=proxies)
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/api.py", line 88, in post
return request('post', url, data=data, **kwargs)
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/sessions.py", line 383, in request
resp = self.send(prep, **send_kwargs)
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/sessions.py", line 486, in send
r = adapter.send(request, **kwargs)
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/adapters.py", line 381, in send
raise ProxyError(e)
ProxyError: Cannot connect to proxy. Socket error: [Errno 54] Connection reset by peer.

【问题讨论】:

  • 找不到任何奇怪的代码。该错误似乎表明存在连接问题。 curl 或 wget 在同一台机器上工作吗?
  • 这里也是玩代理的好工具。 charlesproxy.com

标签: python https python-requests


【解决方案1】:

2019 年 6 月编辑:此回复不再相关。问题已修复。

编辑2:“请注意,即使对于https代理,代理地址的方案也是http,这是因为客户端和代理服务器以纯http发起隧道(CONNECT方法)。但是, 3 年前这可能不是真的。” - 来自 cmets

HTTPS 在请求中被“窃听”。我不知道具体情况,但您可以在此网站上找到有关此问题的其他一些主题。还有一个 Github 问题仍然有效here。我怀疑你遇到了那里提到的问题。如果我完全错了,请有人纠正我。

验证:

$~ curl --proxy https://27.254.52.99:8080 icanhazip.com
27.254.52.99

有效,但在 Python 中:

>>> proxies={'https': 'https://27.254.52.99:8080'}
>>> r = requests.get('http://icanhazip.com', headers={'User-Agent': 'Bla'}, proxies=proxies)
print r.content
<my ipv6 address comes up>

如您所见,我的地址出现了,这意味着代理什么也没做。

我不明白您为什么会收到堆栈跟踪。可能是因为您的 API 也在 HTTPS 上(?)。或者,也许您的 API 只是……关闭了。

无论如何,如果它通过 HTTP,代理确实可以在请求中工作。

>>> proxies={'http': 'http://27.254.52.99:8080'}
>>> r = requests.head('http://icanhazip.com', headers={'User-Agent': 'Bla'}, proxies=proxies)
print r.content
27.254.52.99

【讨论】:

  • @Lance:运气好了吗?
  • 抱歉耽搁了。是的,这对我有用。谢谢。
  • 你们都误解了什么是 https 代理。正确的形式应该是 {'https': 'example.com:3128'},注意 http 部分
  • @ospider 这与我的第一个示例有何不同?此外,这个答案是基于 3 年前 requests 的一个错误。
  • 请注意,即使对于https代理,代理地址的方案也是http,这是因为客户端和代理服务器以纯http发起隧道(CONNECT方法)。然而,这在 3 年前可能不是真的。
猜你喜欢
  • 2017-12-23
  • 1970-01-01
  • 2017-08-01
  • 2023-03-22
  • 2022-07-08
  • 2014-03-03
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多