Python 解决ValueError: check_hostname requires server_hostname

项目场景:

测试爬虫时需要挂代理,在Charles上测试一下。

问题描述:

这是requests挂代理的代码:

proxies = {
    'http': 'http://127.0.0.1:8888',
    'https': 'https://127.0.0.1:8888'
}

response = requests.get(url=api, data=api_data, headers=headers, proxies=proxies)

运行后竟出抛出异常:ValueError: check_hostname requires server_hostname


原因分析:

requests的依赖库urllib3前不久更新导致的问题,urllib3 1.26之前的版本是可以正常运行的,我的版本是1.26.6

解决方案:

将代理字典改写成如下方式:

proxies = {'https': 'http://127.0.0.1:8888'}

为了让之前的老代码能够很好的兼容,也可以直接降低urllib3的版本

pip install urllib3==1.25.11

相关链接

https://stackoverflow.com/questions/66642705/why-requests-raise-this-exception-check-hostname-requires-server-hostname
https://github.com/urllib3/urllib3/issues/2075

posted @ 2022-04-07 11:26  王舰  阅读(1370)  评论(0编辑  收藏  举报