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

网址: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())
相关推荐
AI_Claude_code16 小时前
ZLibrary访问困境方案四:利用Cloudflare Workers等边缘计算实现访问
javascript·人工智能·爬虫·python·网络爬虫·边缘计算·爬山算法
AI_Claude_code17 小时前
ZLibrary访问困境方案三:Web代理与轻量级转发服务的搭建与优化
爬虫·python·web安全·搜索引擎·网络安全·web3·httpx
深蓝电商API1 天前
代理 IP 池在跨境电商爬虫的使用
爬虫·跨境电商
ZC跨境爬虫1 天前
批量爬取小说章节并优化排版(附完整可运行脚本)
前端·爬虫·python·自动化
AI_Claude_code1 天前
ZLibrary访问困境方案二:DNS-over-HTTPS/TLS配置与隐私保护实践
爬虫·python·网络协议·http·网络安全·https·网络爬虫
小白学大数据1 天前
告别复杂 XPath:DeepSeek+Python 爬虫快速实践
开发语言·爬虫·python·selenium
AI_Claude_code1 天前
ZLibrary访问困境方案六:自建RSS/Calibre内容同步服务器的完整指南
运维·服务器·网络·爬虫·python·tcp/ip·http
AI_Claude_code1 天前
安全与合规核心:匿名化、日志策略与法律风险规避
网络·爬虫·python·tcp/ip·安全·http·网络爬虫
专注API从业者2 天前
淘宝商品详情 API 与爬虫技术的边界:合法接入与反爬策略的技术博弈
大数据·数据结构·数据库·爬虫
ZC跨境爬虫2 天前
Scrapy工作空间搭建与目录结构解析:从初始化到基础配置全流程
前端·爬虫·python·scrapy·自动化