这是aiohttp使用的最简单的例子html
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里使用都是十分类似的web
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 信息json
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()