aiohttp中ClientSession使用注意事项

最近在研究协程,想写个协程实现的爬虫,选用aiohttp,对aiohttp中 ClientSession使用有些不解,然而中文资料有点少,大多是写怎么用就没了,不是很详细,就直接看英文官网了。

aiohttp可用作客户端与服务端,写爬虫的话用客户端即可,所以本文只关于aiohttp的客户端使用(发请求),并且需要一点协程的知识才能看懂。

如果想要研究aiohttp的话推荐直接看英文官网,写的很通俗易懂,就算不大懂英文,直接翻译也能看懂七八成了。

如有纰漏,欢迎斧正。

简单请求

如果只发出简单的请求(如只有一次请求,无需cookie,SSL,等),可用如下方法。

但其实吧很少用,因为一般爬虫中用协程都是要爬取大量页面,可能会使得aiohttp报Unclosed client session的错误。这种情况官方是建议用ClientSession(连接池,见下文)的,性能也有一定的提高。

import aiohttp

async def fetch():
    async with aiohttp.request('GET',
            'http://python.org/') as resp:
        assert resp.status == 200
        print(await resp.text())
#将协程放入时间循环        
loop = asyncio.get_event_loop()
loop.run_until_complete(fetch())     

使用连接池请求

一般情况下使用如下示例,由官网摘抄。

import aiohttp
import asyncio

#传入client使用
async def fetch(client,url):
    async with client.get(url) as resp:
        assert resp.status == 200
        return await resp.text()

async def main():
    async with aiohttp.ClientSession() as client:
        html = await fetch(client,url)
        print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())


是不是感觉有点绕呢,其实平时使用是不必这样将fetch函数抽象出去,可以简单写成下面的简洁示例。

import aiohttp
import asyncio
async def main():
    
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值