Python 带有代理的请求导致 SSLError WRONG_VERSION_NUMBER

Python requests with proxy results in SSLError WRONG_VERSION_NUMBER

我无法在 Python 中使用不同的代理。

我的代码:

import requests

proxies = {
    "https":'https://154.16.202.22:3128',
    "http":'http://154.16.202.22:3128'
    }

r=requests.get('https://httpbin.org/ip', proxies=proxies)
print(r.json()) 

我得到的错误是:

.
.
.
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /ip (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1122)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
 
  .
  .
  .
requests.exceptions.SSLError: HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /ip (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1122)')))

我执行了pip install requests.

我执行了 pip uninstall pyopenssl,然后尝试 pip install 旧版本的 pyopenssl 但它没有用。

为什么这不起作用?

您使用的代理根本不支持代理 https:// URLs:

$ https_proxy=http://154.16.202.22:3128 curl -v https://httpbin.org/ip
*   Trying 154.16.202.22...
* TCP_NODELAY set
* Connected to (nil) (154.16.202.22) port 3128 (#0)
* Establish HTTP proxy tunnel to httpbin.org:443
> CONNECT httpbin.org:443 HTTP/1.1
> Host: httpbin.org:443
> User-Agent: curl/7.52.1
> Proxy-Connection: Keep-Alive
> 
< HTTP/1.1 400 Bad Request

除此之外,代理本身的 URL 是错误的 - 即使您代理 HTTPS 流量,它也应该是 http://.. 而不是 https://..。但是 requests 实际上完全忽略了给定的协议,所以这个错误不是问题的原因。但只是为了证明如果代理本身通过​​ HTTPS 访问(如 URL 建议的那样),它也不会工作:

$ https_proxy=https://154.16.202.22:3128 curl -v https://httpbin.org/ip
*   Trying 154.16.202.22...
* TCP_NODELAY set
* Connected to (nil) (154.16.202.22) port 3128 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
* Curl_http_done: called premature == 0
* Closing connection 0
curl: (35) error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

所以这里的解决方法是使用不同的代理,一个实际上支持代理的代理 https:// URLs.

问题的发生是由于最新的 urllib3 中的错误(我在 1.26.3 版本中发现了它)。尝试通过 pip3 install urllib3==1.23 降级到 1.23,它应该可以解决问题。