python [SSL: DH_KEY_TOO_SMALL] dh key too small 错误
requests、httpx出现错误
[SSL: DH_KEY_TOO_SMALL] dh key too small (_ssl.c:1010)
则将requests换成httpx库
然后设置如下代码即可解决上面错误问题
# -*- coding:utf-8 -*-
import httpx
import ssl
class HttpxTest:
def __init__(self):
self.user_agent = ('Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; '
'.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; rv:11.0) like Gecko)')
self.context = ssl.create_default_context()
self.context.set_ciphers("ECDHE")
self.url_params = {}
headers = {
'User-Agent': self.user_agent
}
self.url_params['headers'] = headers
self.url_params['params'] = None
def do_request(self, url, params, request_type):
with httpx.Client(verify=self.context) as client:
if request_type == 'POST':
self.url_params['params'] = params
response = client.post(url, **self.url_params)
elif request_type == 'GET':
response = client.get(url, **self.url_params)
if response is not None:
print(response.text)
if __name__ == '__main__':
url = 'https://www.baidu.com'
httpxTest = HttpxTest()
httpxTest.do_request(url=url, params={}, request_type='GET')
如果上面 https:// 的请求提示错误信息
httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)
则需要在上面代码基础上加上
self.context.check_hostname = False
self.context.verify_mode = ssl.CERT_NONE
完整代码如下
# -*- coding:utf-8 -*-
import httpx
import ssl
class HttpxTest:
def __init__(self):
self.user_agent = ('Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; '
'.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; rv:11.0) like Gecko)')
self.context = ssl.create_default_context()
self.context.check_hostname = False
self.context.verify_mode = ssl.CERT_NONE
self.context.set_ciphers("ECDHE")
self.url_params = {}
headers = {
'User-Agent': self.user_agent
}
self.url_params['headers'] = headers
self.url_params['params'] = None
def do_request(self, url, params, request_type):
with httpx.Client(verify=self.context) as client:
if request_type == 'POST':
self.url_params['params'] = params
response = client.post(url, **self.url_params)
elif request_type == 'GET':
response = client.get(url, **self.url_params)
if response is not None:
print(response.text)
if __name__ == '__main__':
url = 'https://www.baidu.com'
httpxTest = HttpxTest()
httpxTest.do_request(url=url, params={}, request_type='GET')
更多精彩内容 请关注公众号


浙公网安备 33010602011771号