python遇到ValueError: check_hostname requires server_hostname解决方案

冀永寿
2023-12-01

遇到的问题

ValueError: check_hostname requires server_hostname

具体报错内容如下:

Traceback (most recent call last):
  File "pythonrepos.py", line 6, in <module>
    r = requests.get(url, headers=headers)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\urllib3\connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\urllib3\connectionpool.py", line 964, in _prepare_proxy
    conn.connect()
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\urllib3\connection.py", line 359, in connect
    conn = self._connect_tls_proxy(hostname, conn)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\urllib3\connection.py", line 500, in _connect_tls_proxy
    return ssl_wrap_socket(
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  File "C:\Users\m1521\AppData\Roaming\Python\Python38\site-packages\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
    return ssl_context.wrap_socket(sock)
  File "D:\Program Files\Python38\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "D:\Program Files\Python38\lib\ssl.py", line 997, in _create
    raise ValueError("check_hostname requires server_hostname")
ValueError: check_hostname requires server_hostname

所执行的代码如下,该代码产生上述错误:

import requests

# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f"Status code: {r.status_code}")

# 将API响应赋给一个变量
response_dict = r.json()

# 处理结果
print(response_dict.keys())

解决方法

这个问题的原因是urllib3版本太高,新版的urllib3修改了一些东西,所以会报错。下面的解决办法是降低urlib3的版本。

打开命令行,运行:

pip install urllib3==1.25.11

如果成功,则完成;如果不成功,报错如下,则继续阅读。

Defaulting to user installation because normal site-packages is not writeable
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1125)'))': /simple/urllib3/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1125)'))': /simple/urllib3/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1125)'))': /simple/urllib3/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1125)'))': /simple/urllib3/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1125)'))': /simple/urllib3/
Could not fetch URL https://pypi.org/simple/urllib3/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/urllib3/ (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1125)'))) - skipping
ERROR: Could not find a version that satisfies the requirement urllib3==1.25.11
ERROR: No matching distribution found for urllib3==1.25.11

可以使用

pip install urllib3==1.25.11 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

意思是通过国内的源来安装,速度快并且不会出现连接问题。

显示安装成功

PS D:\user\文档\python\python_work\data_visualization\download_data>  pip install urllib3==1.25.11 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
>>
Defaulting to user installation because normal site-packages is not writeable
Looking in indexes: http://pypi.douban.com/simple
Collecting urllib3==1.25.11
  Downloading http://pypi.doubanio.com/packages/56/aa/4ef5aa67a9a62505db124a5cb5262332d1d4153462eb8fd89c9fa41e5d92/urllib3-1.25.11-py2.py3-none-any.whl (127 kB)
     |████████████████████████████████| 127 kB 3.3 MB/s
Installing collected packages: urllib3
  Attempting uninstall: urllib3
    Found existing installation: urllib3 1.26.4
    Uninstalling urllib3-1.26.4:
      Successfully uninstalled urllib3-1.26.4
Successfully installed urllib3-1.25.11
PS D:\user\文档\python\python_work\data_visualization\download_data>

然后运行自己的程序,成功!

Status code: 200
dict_keys(['total_count', 'incomplete_results', 'items'])

参考

[1]https://stackoverflow.com/questions/66642705/why-requests-raise-this-exception-check-hostname-requires-server-hostname

 类似资料: