概述

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

安装

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

1
pip install aiohttp

用法

发送请求

1
2
3
4
5
6
7
8
9
import aiohttp
import asyncio

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

获取html内容

1
await resp.text()

获取json

1
await resp.json()

获取图片内容

1
await resp.content.read()

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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())