# encoding: utf-8 # 内置模块 用于创建文件 import os import parsel import requests import re def get_response(html_url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' } response = requests.get(url=html_url, headers=headers) # 万能转码方式 response.encoding = response.apparent_encoding return response def get_image_url(hero_id): # 英雄详情页URL # https://pvp.qq.com/web201605/herodetail/106.shtml # f 字符串格式化,等同于 'https://pvp.qq.com/web201605/herodetail/{}.shtml'.format(hero_id) hero_url = f'https://pvp.qq.com/web201605/herodetail/{hero_id}.shtml' # 请求网页数据 response = get_response(hero_url) # 转换成 Selector 对象 selector = parsel.Selector(response.text) # 提取英雄名字 hero_name = selector.css('.cover-name::text').get() # 正则表达式 提取所有皮肤名字 split 字符串分割 分割之后返回的是一个列表 skin_name = re.findall('<ul class="pic-pf-list pic-pf-list3" data-imgname="(.*?)">', response.text)[0].split('|') # len() 计算有多少个元素 num = len(skin_name) # for 循环 也称遍历 左闭右开 int() 转换成整数类型 a = 0 for page in range(1, int(num) + 1): a = a + 1 # 皮肤图片地址 # https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/106/106-bigskin-2.jpg image_url = f'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{hero_id}/{hero_id}-bigskin-{page}.jpg' # 请求皮肤 图片地址,图片是二进制的数据 所以是取 content image_content = get_response(image_url).content # 相对路径 传入英雄名字 给文件夹命名 # path = f'{hero_name}\\' path = r'D:\1\\' path1 = path+f'{hero_name}\\' # 判断路径下面是否有这个文件夹,如果没有就创建文件夹 if not os.path.exists(path1): os.makedirs(path1) # 皮肤图片保存的路径 文件夹 + skin_name[int(page) - 1].split('&')[0] 皮肤名字 filename = path1 + skin_name[int(page) - 1].split('&')[0] + '.jpg' # filename 路径 mode 模式 wb 二进制的形式 as 重命名 with open(filename, mode='wb') as f: # write 写入保存 f.write(image_content) print(a,"、",f'正在保存:{hero_name}', skin_name[int(page) - 1].split('&')[0] ) if __name__ == '__main__': # 英雄数据的接口数据URL url = 'https://pvp.qq.com/web201605/js/herolist.json' # 返回数据 为json数据 json_data = get_response(url).json() # 是一个列表包含 一个一个的字典数据 遍历获得 没一个字典数据 for i in json_data: # 根据字典取值 提取每个英雄的ID hero_id = i['ename'] # 调用函数 传入英雄ID get_image_url(hero_id)