Aiohttp
2021-03-29发布
|

概述

aiohttp和requests类似,都是发送http请求的。不同的是requests是同步操作,会阻塞IO。而aiohttp是异步操作,不会阻塞IO

安装

aiohttp是第三方库,用之前需要先安装:

pip install aiohttp

用法

发送请求

import aiohttp
import asyncio

url = 'https://网址'
# 创建请求对象
session = async aiohttp.ClientSession()
# 发送get请求
resp = async session.get(url)

获取html内容

await resp.text()

获取json

await resp.json()

获取图片内容

await resp.content.read()

例子

import aiohttp
import asyncio

urls = [
    'http://kr.shanghai-jiuxin.com/file/bizhi/20210321/4bld1qgv0za.jpg',
    'http://kr.shanghai-jiuxin.com/file/bizhi/20210321/er34ofpghzl.jpg',
    'http://kr.shanghai-jiuxin.com/file/bizhi/20210321/y2tqmeteal0.jpg',
    'http://kr.shanghai-jiuxin.com/file/bizhi/20210321/2bvexowkvrb.jpg',
]


async def down(url):
    name = url.split('/')[-1]
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
              # 打开一个文件,并赋予写权限
            with open('./img/' + name, mode='wb') as f:
                  # 把得到的图片文件存入f中
                f.write(await resp.content.read())


async def main():
    tasks = []
    for url in urls:
        tasks.append(down(url))
    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())


------------ END ------------