必应美图-异步爬虫-asyncio协程

# -*- ecoding: utf-8 -*-
# @ModuleName: 2、必应美图爬虫-协程异步
# @Function:
# @Author: merry
# @Time: 2021年01月24日13:59:34
import aiohttp
import os
import asyncio
import requests
import time

# 定义请求头,不传cookie,可能报错为:
# json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
    'Cookie': 'Hm_lvt_ea4269d8a00e95fdb9ee61e3041a8f98=1609402420,1609745653,1610861384; wzws_cid=3ffd06525b6a5d7c60c531609c74580f45f46c0771558102e3f6fe7adb6701ec89fe9e638a9d38ccead653f87d12df7aa1e5ceebaab13706edfc0ce466bd78b6ff6b6ca7beae366aedd186dcd942ce82'
}
# 这个URL获取图片的个数
url = 'http://lab.mkblog.cn/wallpaper/api.php?cid=6&start=0&count=30'
# 返回的json中获取total条数
total = requests.get(url, headers=headers).json()['total']
# 总条数/每页显示的条数 = 总共页数
pageTotal = int(total)
print('总条数', pageTotal)
# 创建存储图片的文件夹
if not os.path.exists('./img'):
    os.mkdir('img')
# 定义剩余的页数

#  循环请求所有图片
for i in range(0, pageTotal, 30):
    print('i的值为', i)
    url = f'http://lab.mkblog.cn/wallpaper/api.php?cid=6&start={i}&count=30'
    # 获取响应json
    reponse = requests.get(url, headers=headers).json()
    # 获取data列表
    new_img_list = reponse['data']


    # 定义异步方法
    async def get_img(url, session):
        try:
            # 异常捕获,个别图片获取不到utag名称,获取不到的使用tag标签作为图片名称
            imgName = url['utag'] + '.jpg'
        except KeyError:
            imgName = url['tag'] + '.jpg'
        # 获取 分辨率为img_1600_900质量图片的url
        imgUrl = url['img_1600_900']
        # 使用异步请求模块aiohttp进行网络请求
        async with await session.get(imgUrl, headers=headers) as reponse:
            # 请求上一步的URL,获取二进制编码
            imgResponse = await reponse.read()
        # 将二进制编码写入到img文件夹
        with open(f'./img/{imgName}', 'wb') as fp:
            fp.write(imgResponse)
            print(f'33[32m下载{imgName}完成')


    # 异步主方法
    async def main():
        # 创建一个aiohttp session异步对象,此对象有async with,必须定义在异步方法当中
        async with aiohttp.ClientSession() as session:
            # 使用列表生成式创建get_img任务对象
            tasks = [asyncio.create_task(get_img(url, session)) for url in new_img_list]
            await asyncio.wait(tasks)


    # 执行主方法
    asyncio.run(main())
    # 睡眠一秒防止过快
    time.sleep(1)

原文地址:https://www.cnblogs.com/merryblogs/p/14320752.html