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

网址: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())
相关推荐
cipher4 天前
crawl4ai:AI时代的数据采集利器——从入门到实战
后端·爬虫·python
深蓝电商API4 天前
结构化数据提取:XPath vs CSS 选择器对比
爬虫·python
易辰君5 天前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
深蓝电商API5 天前
爬虫增量更新:基于时间戳与哈希去重
爬虫·python
电商API_180079052475 天前
京东商品评论API接口封装的心路历程
服务器·开发语言·爬虫·数据分析·php
袁袁袁袁满5 天前
Haystack与亮数据MCP工具结合实现自动化爬虫
爬虫·python·网络爬虫·数据采集·爬虫实战·视频爬虫·特推爬虫
深蓝电商API5 天前
Redis 作为爬虫去重与任务队列实战
爬虫·python
IP搭子来一个5 天前
爬虫使用代理IP全解析:原理、类型与实战指南
爬虫·网络协议·tcp/ip
iFeng的小屋5 天前
【2026最新xhs爬虫】用Python批量爬取关键词笔记,异步下载高清图片!
笔记·爬虫·python
嫂子的姐夫6 天前
030-扣代码:湖北图书馆登录
爬虫·python·逆向