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

网址: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())
相关推荐
Chengbei1121 小时前
JsOwl|AI 赋能 JS 敏感信息扫描器,AST + 正则、source‑map 源码还原、登录态爬虫输出交互式 HTML 报告
开发语言·javascript·网络·人工智能·爬虫·网络安全·自动化
远航计算机1 天前
AI 答案里的链接,为什么开始分等级了?
大数据·人工智能·爬虫·aigc
Novproxy_Z1 天前
爬虫任务被拦截:区分 IP 封禁、设备封禁、账号封禁
爬虫·网络协议·tcp/ip
郝学胜-神的一滴1 天前
Python浏览器自动化:Selenium与Playwright实战对比,网页爬虫&自动操作一站式指南
开发语言·爬虫·python·selenium·程序人生·自动化
Python大数据分析@2 天前
通过 MCP 实现 AI Agent自动化数据采集
运维·人工智能·爬虫·自动化
深蓝电商API2 天前
Docker+K8s部署爬虫:从单机到集群的完整路线
爬虫·docker·k8s
深蓝电商API2 天前
亿级数据的存储选型:MongoDB/ES/ClickHouse横评
爬虫·clickhouse·mongodb·elasticsearch
重生之高冷汉堡包3 天前
YouTube 数据抓取出现 429/403 错误?2026 反爬机制拆解与爬虫选型指南
爬虫
钱栈up3 天前
扫完 3.5 万文件后,我发现了 521 组散落的同名文件
爬虫·python·数据分析
B2_Proxy3 天前
aiohttp 异步爬虫如何配置代理?连接池复用与超时控制实战
爬虫