强大的aiohttp异步爬虫的使用

aiohttp是一个为Python提供异步HTTP 客户端/服务端编程,基于asyncio(Python用于支持异步编程的标准库)的异步库。

爬虫方面我们用的主要是客户端来发起请求,一般我们使用aiohttp和asyncio联合这两个异步库来写异步爬虫,其实可以把aiohttp 看作是异步版的requests库。

这是aiohttp使用的最简单的例子

import aiohttp
import asyncio

async def main():
	#我们得到一个session会话对象,由ClientSession赋值得到
	async with aiohttp.ClientSession() as session:
		#使用session.get方法得到response(response是一个CilentResponse对象)
		async with session.get("https://baidu.com") as response:
			print(response.status)
			print(await response.text)

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

要注意的是由于这是异步库,要实现异步必须全部使用async/await 异步语法
其实对于session对象的操作比如get,post获得json数据等等http方法的使用和在requests里使用都是十分相似的

下面记流水仗了

  • 传递参数
async with session.get(url, params = dict) as response:

注意的是aiohttp会在发送请求前标准化URL。 域名部分会用IDNA 编码,路径和查询条件会重新编译(requoting)。如果服务器需要接受准确的表示并不要求编译URL,那标准化过程应是禁止的。 禁止标准化可以使用encoded=True:

await session.get(URL('http://example.com/%30', encoded=True))
  • 文本的解码
await resp.text(encoding='utf-8')
  • 文件的读取
await response.read()
await response.text()
await response.json()
  • 获取流式响应内容
await response.content.text()

return 信息

import aiohttp
import asyncio

async def main():
    # 好像必须写一个并发数,否则无法return
    async with asyncio.Semaphore(5):
        async with aiohttp.ClientSession() as session:
            async with session.get("https://baidu.com") as html:
                response = await html.text(encoding = 'utf-8')
                return response
            

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

原文地址:https://www.cnblogs.com/yfc0818/p/11072638.html