最近在研究协程,想写个协程实现的爬虫,选用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():