在使用aiohttp的过程中,访问https网站遇到了ssl报错的问题,说证书验证不通过,报错如下:
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host s.weibo.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)')]
这个时候需要我们先声明一个aiohttp的连接器对象,并且不校验ssl证书,之后的请求都使用这个连接器去发起,就不会再校验证书了
具体代码如下:
# -*- coding:utf-8 -*-
# 微博热搜
import asyncio
import aiohttp
async def fetch(url):
conn=aiohttp.TCPConnector(verify_ssl=False) # 防止ssl报错
async with aiohttp.request('GET',url, connector=conn) as resp:
if resp.status != 200:
return ''
return await resp.text()
async def run():
url = 'https://s.weibo.com/top/summary'
html = await fetch(url)
return html
if __name__ == "__main__":
loop = asyncio.get_event_loop()
res = loop.run_until_complete(run())
print(res)