爬虫的异步实现aiohttp库学习
在协程基础学习(python协程基础学习)中,我们学习到requests。get()也会使程序处入阻塞状态,从而无法实现异步。因此需要引入提供异步Web服务的aiohttp库。
由此异步中的网页请求与同步操作中的网页请求requests。get()的python写法不一样,下面通过下述例子带领大家学习aiohttp库的使用以及爬虫的异步实现。importasyncioimportaiohttpasyncdefdownload(url,name):asyncwithaiohttp。ClientSession()assession:asyncwithsession。get(url)asresp:withopen(name,modew,encodingutf8)asf:f。write(awaitresp。text())asyncdefmain():urls〔http:www。baidu。com,http:www。bilibili。com,http:www。163。com〕names〔baidu,bilibili,163〕tasks〔〕forindexinrange(len(urls)):tasks。append(asyncio。createtask(download(urls〔index〕,names〔index〕)))awaitasyncio。wait(tasks)ifnamemain:asyncio。run(main())会报错loopasyncio。neweventloop()asyncio。seteventloop(loop)loop。rununtilcomplete(main())
其中需要注意的在于:
1。aiohttp。ClientSession()的作用等同于同步中的requests
2。session。get(url)很好理解就是requests。get()
3。awaitresp。text()的作用等同于同步中的resp。text。此外异步中resp。content。read()就等同于resp。content
4。asyncio。run(main())运行会报错(见下图),解决方法见代码。
代码运行结果如下:
头条创作挑战赛