爬虫的异步实现-aiohttp库学习

在协程基础学习(python协程基础学习)中,我们学习到requests.get()也会使程序处入阻塞状态,从而无法实现异步。因此需要引入提供异步 Web服务的aiohttp库。

由此异步中的网页请求与同步操作中的网页请求requests.get()的python写法不一样,下面通过下述例子带领大家学习aiohttp库的使用以及爬虫的异步实现。

import asyncio
import aiohttp

async def download(url,name):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            with open(name,mode='w',encoding='utf-8') as f:
                f.write(await resp.text())

async def main():
    urls = [
        "http://www.baidu.com",
        "http://www.bilibili.com",
        "http://www.163.com"
    ]
    names = ['baidu', 'bilibili', '163']
    tasks = []
    for index in range(len(urls)):
        tasks.append(asyncio.create_task(download(urls[index],names[index])))
    await asyncio.wait(tasks)

if __name__ == "__main__":
    #asyncio.run(main())  会报错
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())

其中需要注意的在于:
1.aiohttp.ClientSession()的作用等同于同步中的requests
2.session.get(url)很好理解就是requests.get()
3.await resp.text()的作用等同于同步中的resp.text。此外异步中resp.content.read()就等同于resp.content
4.asyncio.run(main())运行会报错(见下图),解决方法见代码。

代码运行结果如下:

#头条创作挑战赛#

展开阅读全文

页面更新:2024-03-02

标签:爬虫   挑战赛   下图   写法   例子   状态   作用   代码   网页   基础

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top