python程式碼錯誤RuntimeError: Session is closed

Joy and courage發表於2020-10-07

我在使用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())

執行:
執行成功

相關文章