項目場景:
測試爬蟲時需要掛代理,在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
