开 前言嗨喽!大家好呀,这里是魔王~ 开发环境以及模块的使用:本次整体爬虫流程:确定目标需求 英雄联盟所有英雄皮肤图片 找到一张英雄皮肤图片的来源 https://game./images/lol/act/img/skin/big1000.jpg 找这个英雄所有的图片来源是在哪? 安妮: https://game./images/lol/act/img/js/hero/1.js 奥拉夫: https://game./images/lol/act/img/js/hero/2.js 找到所有英雄ID https://game./images/lol/act/img/js/heroList/hero_list.js 对 url地址发送请求 获取数据 解析数据 获取想要内容 获取英雄ID 把英雄传入 https://game./images/lol/act/img/js/hero/{}.js 获取英雄皮肤图片 url 地址 / 英雄名字/ 皮肤名字 保存数据, 图片保存到本地文件夹
完整代码import requests # 第三方模块 pip install requests import pprint # 格式化输出的模块 在打印json的数据的时候,可以更加方便 查看数据信息 import os # 内置模块 不需要安装 自带的 import re # 内置模块 不需要安装
# 对 url地址发送请求 获取数据 url = 'https://game./images/lol/act/img/js/heroList/hero_list.js' # 需要要加一个请求头? 伪装浏览器发送请求 # 请求头 是一个字典的数据 一个关键字 对应一个值 headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36' }
def change_title(title): mode = re.compile(r'[\\\/\:\*\?\"\<\>\|]') new_title = re.sub(mode, '_', title) return new_title
def save(title, name, img_url): # 我想要把每个英雄皮肤图片,单独保存在一个文件里面 filename = f'{title}\\' # 自动创建文件夹 # 如果没有这个文件夹 / 没有这个路径 那么就创建这个文件夹 if not os.path.exists(filename): os.mkdir(filename) # 获取图片内容,是要获取它一个二进制数据内容 # 文本数据 response.text json数据 response.json() 二进制数据 response.content img_content = requests.get(url=img_url, headers=headers).content with open(filename + name + '.jpg', mode='wb') as f: f.write(img_content) print(name)
response = requests.get(url=url, headers=headers) # pprint.pprint(response.json()) # 解析数据 获取 英雄ID # json数据提取数据 和 字典类似 根据关键字提取值 通俗的讲 根据冒号左边的内容 提取冒号右边的内容 hero_list = response.json()['hero'] # 返回的数据内容 是列表形式 # 通过遍历/for 循环 提取它每一个英雄ID
lis = [] for index in hero_list:
hero_id = index['heroId'] lis.append(hero_id) # 字符串 格式化方法 # 对英雄的皮肤数据 url地址 发送请求 获取英雄皮肤图片数据
lis = lis[27:]
for li in lis: hero_url = 'https://game./images/lol/act/img/js/hero/{}.js'.format(li) response_1 = requests.get(url=hero_url, headers=headers) # pprint.pprint(response_1.json()) # 解析数据 获取英雄皮肤url地址/英雄名字/皮肤名字 skins = response_1.json()['skins'] for index_1 in skins: # 皮肤图片地址 img_url = index_1['mainImg'] # 英雄名字 title = index_1['heroTitle'] # 皮肤名字 name = index_1['name'] new_name = change_title(name) new_title = change_title(title)
if img_url: save(new_title, new_name, img_url) else: chroma_img = index_1['chromaImg'] save(new_title, new_name, chroma_img)
尾语好了,我的这篇文章写到这里就结束啦! 有更多建议或问题可以评论区或私信我哦!一起加油努力叭(ง ·_·)ง 喜欢就关注一下博主,或点赞收藏评论一下我的文章叭!!!
|