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

网址: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())
相关推荐
煤炭里de黑猫3 小时前
Python爬虫开发实战指南:从基础到高级工具应用
人工智能·爬虫
深蓝电商API4 小时前
Selenium Grid分布式执行爬虫任务
爬虫·python·selenium
天天进步20154 小时前
生产级部署:如何结合 Docker 快速上线你的 Botasaurus 爬虫服务
爬虫·云原生
深蓝电商API4 小时前
Selenium结合Chrome DevTools协议加速爬取
爬虫·python·selenium·测试工具·chrome devtools
煤炭里de黑猫5 小时前
Python 爬虫进阶:利用 Frida 逆向移动端 App API 以实现高效数据采集
开发语言·爬虫·python
喵手20 小时前
Python爬虫零基础入门【第七章:动态页面入门(Playwright)·第3节】优先 API:用 Network 找接口,回到 Requests(更稳定)!
爬虫·python·playwright·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·优先 api
喵手1 天前
Python爬虫零基础入门【第六章:增量、去重、断点续爬·第3节】幂等去重:同一条数据反复跑也不会重复入库!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·增量、去重、断点续爬·幂等去重
深蓝电商API1 天前
Selenium多窗口切换与Cookie管理
爬虫·python·selenium·测试工具
喵手1 天前
Python爬虫零基础入门【第六章:增量、去重、断点续爬·第1节】增量采集:只抓新增/更新(新手也能做)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·增量、去重·增量采集