1.背景

image.png

2.python 异步IO库介绍:asyncio

image.png

  1. import asyncio
  2. import aiohttp
  3. from main import timethis
  4. urls = [
  5. f'https://www.cnblogs.com/sitehome/p/{page}'
  6. for page in range(1,10)
  7. ]
  8. async def async_craw(url):
  9. print('start craw url',url)
  10. async with aiohttp.ClientSession() as session:
  11. async with session.get(url) as resp:
  12. result = await resp.text()
  13. print(f'end craw url:{url},{len(result)}')
  14. loop = asyncio.get_event_loop()
  15. tasks = [
  16. loop.create_task(async_craw(url))
  17. for url in urls
  18. ]
  19. @timethis
  20. def do_main():
  21. loop.run_until_complete(asyncio.wait(tasks))
  22. if __name__ == '__main__':
  23. do_main()