我在使用aiohttp库和asyncio库进行协程下载图片时报出错误RuntimeError: Session is closed 我的代码如下
import aiohttp import asyncio async def fetch(session,url): print('开始下载图片:',url) async with session.get(url,verify_ssl=False)as response: conent = await response.content.read() file_name = url[-16:] with open(file_name,mode='wb')as fp: fp.write(conent) async def main(): async with aiohttp.ClientSession() as session: url_list = [ 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=231146236,2859633049&fm=26&gp=0.jpg', 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2194951532,1309127690&fm=26&gp=0.jpg', 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602084713475&di=20def259a9a44f66c1eed626732e67a2&imgtype=0&src=http%3A%2F%2Fh.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2Fdc54564e9258d1090c1b7aead158ccbf6d814dea.jpg', ] tasks = [asyncio.create_task(fetch(session,url))for url in url_list] await asyncio.wait(tasks) if __name__ == '__main__': asyncio.run(main())然后就一直报出错误:RuntimeError: Session is closed 后来去网上查资料发现这个错误应该不是服务器的问题,而是自己代码块有问题,后来我仔细看了一下自己的代码,发现是因为我的缩进出现了问题 然后正确的代码应该是
import aiohttp import asyncio async def fetch(session,url): print('开始下载图片:',url) async with session.get(url,verify_ssl=False)as response: conent = await response.content.read() file_name = url[-16:] with open(file_name,mode='wb')as fp: fp.write(conent) async def main(): async with aiohttp.ClientSession() as session: url_list = [ 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=231146236,2859633049&fm=26&gp=0.jpg', 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2194951532,1309127690&fm=26&gp=0.jpg', 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602084713475&di=20def259a9a44f66c1eed626732e67a2&imgtype=0&src=http%3A%2F%2Fh.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2Fdc54564e9258d1090c1b7aead158ccbf6d814dea.jpg', ] tasks = [asyncio.create_task(fetch(session,url))for url in url_list] await asyncio.wait(tasks) if __name__ == '__main__': asyncio.run(main())运行: