协程爬虫案例: 王者荣耀英雄皮肤图片爬取

网址:https://pvp.qq.com/web201605/herolist.shtml

现在我们需要使用协程爬取皮肤图片。

我们进入这个网址然后打开开发者工具。我们看到

在网络的Fetch/XHR中,有个heroskinlist.jso的文件请求。我们下载下来就发现是一串json数据。其中的一小段数据是这样的

在json数据中的fmlb_4536中就是他的皮肤图片地址,我们请求后下载到指定的文件就可以了。接下来我们看看程序实现。

python 复制代码
import os
import asyncio
import aiofile
import aiohttp


class HeroSpider:
    def __init__(self):
        self.json_url = 'https://pvp.qq.com/zlkdatasys/heroskinlist.json'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
        }


    async def get_image_content(self, session, name, skin_url):
        try:
            async with session.get(skin_url, headers=self.headers ) as response:
                if response.status == 200:
                    content = await response.read()
                    async with aiofile.async_open('./images/{}.jpg'.format(name), 'wb') as f:
                        await f.write(content)
                        print('下载成功:{}'.format(name))
                else:
                    print(f'HTTP错误 {response.status}: {name}')
        except Exception as e:
            print(f'下载失败 {name}: {e}')

    async def main(self):
        tasks = []
        async with aiohttp.ClientSession() as session:
            async with session.get(self.json_url, headers=self.headers) as response:
                result = await response.json(content_type=None)
                for item in result['pflb20_3469']:
                    name = item['pfmclb_7523']
                    url = item['fmlb_4536']
                    print(f'正在下载:{name}, URL: {url}')
                    con_j = asyncio.create_task(self.get_image_content(session, name, url))
                    tasks.append(con_j)
                await asyncio.gather(*tasks)


if __name__ == '__main__':
    if not os.path.exists('./images'):
        os.mkdir('./images')

    spider = HeroSpider()
    asyncio.run(spider.main())
相关推荐
标致的自行车8 小时前
Selenium 爬虫固定开头:
爬虫·selenium·测试工具
深蓝电商API13 小时前
Flutter App逆向初探:Dart编译产物的分析思路
爬虫
taocarts_bidfans2 天前
Playwright 浏览器指纹伪装 + 住宅代理池 日系电商爬虫防封禁实战
爬虫·bidfans
许彰午2 天前
73_Python爬虫Scrapy框架入门
爬虫·python·scrapy
深蓝电商API2 天前
模拟器批量操控:雷电/夜神 + ADB集群方案
数据仓库·爬虫·adb
许彰午2 天前
72_Python爬虫基础BeautifulSoup
爬虫·python·beautifulsoup
阿标在干嘛2 天前
政策快报爬虫的生存指南:IP池、浏览器模拟、验证码识别实战
爬虫·网络协议·tcp/ip
胡渠洋3 天前
初识python爬虫
爬虫
huangdong_3 天前
电商图片下载工具横向对比深度评测:固乔、FATKUN、图快、当图、淘蛙、存图宝、火蚁一键存图七款工具全面解析
数据库·爬虫
Caco_D13 天前
一行代码抓遍全网 20 个热榜!Aneiang.Pa 4.0 发布 — 极简 .NET 爬虫库
爬虫·.net