Python通过aiohttp多线程下载文件

import asyncio
import datetime
import time
import aiohttp
from aiohttp.client_exceptions import ClientConnectorError

# 替换链接地址list
urls = [

]

async def download(url):
    filename = url.split('/')[-1]
    print(f"Downloading {filename}...")
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url) as response:
                with open(f"./runtime/download/{filename}", 'wb') as f:
                    f.write(await response.read())
            print(f"{filename} downloaded.")
        except ClientConnectorError as e:
            print(e)




async def main():
    in_time = time.time()
    # 创建任务列表
    tasks = [asyncio.create_task(download(url)) for url in urls]

    # 等待所有任务完成
    await asyncio.gather(*tasks)

    print("All files downloaded.")
    out_time = time.time()
    print(datetime.timedelta(seconds=out_time - in_time))


# 运行主程序


if __name__ == '__main__':
    print('开始')
    asyncio.run(main())

posted @ 2023-04-17 16:44  _迷途  阅读(181)  评论(0编辑  收藏  举报