python 协程并发下载图片

 1 import aiohttp
2 import asyncio
3 import time
4
5 async def dl_coroutine(session,url):
6 print('开始下载图片%s' + url)
7 async with session.get(url, verify_ssl=False) as res:
8 content = await res.content.read()
9 t = time.time()
10 filename = './img/{}.jpg'.format(int(round(t*1000)))
11 with open(filename,mode='wb') as f:
12 f.write(content)
13 print('下载完成')
14 async def main():
15 async with aiohttp.ClientSession() as session:
16 imglist = [
17 'https://img.tupianzj.com/uploads/allimg/201909/9999/51cdea9e98.jpg',
18 'https://img.tupianzj.com/uploads/allimg/160718/9-160GPZ331.jpg',
19 'https://img.tupianzj.com/uploads/allimg/191210/37-191210143P1.jpg'
20 ]
21 tasks = [ asyncio.create_task(dl_coroutine(session,img)) for img in imglist]
22 await asyncio.wait(tasks)
23 if __name__ == '__main__':
24 t1 = int(round(time.time()*1000))
25 asyncio.run(main())
26 t2 = int(round(time.time()*1000))
27 print('执行了{} 毫秒'.format(t2-t1))
上一篇:Lua协程-测试3


下一篇:从Ubuntu12.04升级到Ubuntu 14.04之后,系统将无法启动