简单介绍 aiohttp 异步请求库
aiohttp 用的是协程, 那么什么是协程呢?
协程是一种用户态的轻量级线程,又称"微线程",英文名Coroutine,协程的调度完全由用户控制。人们通常将协程和子程序(函数)比较着理解。
子程序调用总是一个入口,一次返回,一旦退出即完成了子程序的执行。
协程的起始处是第一个入口点,在协程里,返回点之后是接下来的入口点。
python中拥有协程库 为 asyncio
aiohttp 封装的是 asyncio 库 来完成异步请求
aiohttp的安装
pip install aiohttp
代码时刻
# -*- coding: UTF-8 -*-
import time
import aiohttp
import asyncio
import json
import os
async def download(url):
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
}
# 创建session对象
async with aiohttp.ClientSession(headers=headers) as session:
# 进行请求第一层页面
async with session.get(url) as resp:
html = await resp.text()
html = json.loads(html)
image = await parse(html)
# 判断是否存在image目录 如果不存在进行创建
if not os.path.isdir('./image'):
os.mkdir('./image')
for k, v in image.items():
print(k, '已下载')
# 请求第二层页面(图片)
async with session.get(v) as im:
with open('./image/' + k + '.jpg', 'wb') as f:
while True:
# 以数据流的方式进行存储 (允许每次的最大字节为1024)
chunk = await im.content.read(1024)
if not chunk:
break
f.write(chunk)
async def parse(html):
""" 对网页进行解析 """
image = {}
html = html['data']['datas']
for img_html in html:
name = img_html['nick']
image_url = img_html['screenshot']
image.update({name: image_url})
return image
startTime = time.time()
# 创建任务
task = [asyncio.ensure_future(
download(f'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&gameId=1663&tagAll=0&page={page}')
) for page in range(1, 11)]
# 把任务列表加入到事件循环
loop = asyncio.get_event_loop()
# 开始执行事件
loop.run_until_complete(asyncio.gather(*task))
print(time.time() - startTime)
注: 编程环境 python3.6.5