异步aiohttp爬取Photo

简单介绍 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值