其他分享
首页 > 其他分享> > 爬虫,用协程下载图片中TypeError: a bytes-like object is required, not 'coroutine'

爬虫,用协程下载图片中TypeError: a bytes-like object is required, not 'coroutine'

作者:互联网

async def aio_download(img_url, img_name):
    async with aiohttp.ClientSession() as session:
        async with session.get(img_url) as resp:
            async with aiofiles.open('img/' + img_name, mode='ab') as f:
                await f.write(resp.read())
                print(img_name, "下载完毕!")

刚开始的下载代码是这个样子的,但是程序运行的时候一直报错TypeError,我一直以为是代码里f.write(resp.read())的输入的类型不对,到处找,最后发现是少了一个await的问题最终的代码如下:

async def aio_download(img_url, img_name):
    async with aiohttp.ClientSession() as session:
        async with session.get(img_url) as resp:
            async with aiofiles.open('img/' + img_name, mode='ab') as f:
                img = await resp.read()
                await f.write(img)
                print(img_name, "下载完毕!")

标签:TypeError,name,img,coroutine,resp,await,session,async,like
来源: https://www.cnblogs.com/jenglyon/p/15700796.html