当前位置:   article > 正文

【python爬虫】aiohttp模块的异步协程代码模板_with open(name, mode='w') as f: f.write(await ren.

with open(name, mode='w') as f: f.write(await ren.read())

aiohttp模块的使用:

  1. import aiohttp
  2. import asyncio
  3. urls = [
  4. "",
  5. "",
  6. ""
  7. ]
  8. async def download(url):
  9. name = url.rsplit("/",1)[1]
  10. #发送请求
  11. async with aiohttp.ClientSession() as session:
  12. async with session.get(url) as resp:
  13. with open(name, mode="wb") as f:
  14. f.write(await resp.content.read()) #读取内容为异步的,需要await挂起
  15. print(name,"done!")
  16. async def main():
  17. tasks = []
  18. for url in urls:
  19. tasks.append(download(url))
  20. await asyncio.wait(tasks)
  21. if __name__ == '__main__':
  22. asyncio.run(main())

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/739841
推荐阅读
相关标签
  

闽ICP备14008679号