1.导入所需的包
import requests
from lxml import etree
import os
from time import sleep
2.定义请求头
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'}
3.发送请求
# hero_list_url请求时得到的英雄列表json文件
hero_list_url = 'https://pvp.qq.com/web201605/js/herolist.json'
hero_list_resp = requests.get(hero_list_url,headers=headers)
4.遍历响应的json文件列表,如果英雄的中文名称(cname
)对应的目录不存在,代码会创建这个目录。这是为了将下载的皮肤图片保存到正确的位置。
for h in hero_list_resp.json():
ename=h.get('ename')
cname=h.get('cname')
skin_name=h.get('skin_name')
names=(skin_name.split('|'))
if not os.path.exists(cname):
os.makedirs(cname)
5.为每个皮肤名称发起一个HTTP GET请求,从指定的URL下载图片。URL中的{ename}
和{i+1}
是动态部分,分别代表英雄的英文名称和皮肤的序号,
下载的图片被保存到之前创建的目录中,文件名是皮肤的名称
for i,n in enumerate(names):
resp = requests.get(f'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{ename}/{ename}-bigskin-{i+1}.jpg')
with open(f'{cname}/{n}.jpg','wb') as f:
f.write(resp.content)
print(f'已下载:{cname}的{n}皮肤')
sleep(2)
6.下载完成
7.源码
python
import requests
from lxml import etree
import os
from time import sleep
#伪装
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'}
#发送请求
hero_list_url = 'https://pvp.qq.com/web201605/js/herolist.json'
hero_list_resp = requests.get(hero_list_url,headers=headers)
# print(hero_list_resp.text)
for h in hero_list_resp.json():
ename=h.get('ename')
cname=h.get('cname')
skin_name=h.get('skin_name')
names=(skin_name.split('|'))
if not os.path.exists(cname):
os.makedirs(cname)
# # 访问英雄主页
# hero_info_url = f'https://pvp.qq.com/web201605/herodetail/{ename}.shtml'
# hero_info_resp = requests.get(hero_info_url,headers=headers)
# hero_info_resp.encoding='gbk'
# e = etree.HTML(hero_info_resp.text)
# names = e.xpath('//ul[@class="pic-pf-list pic-pf-list3"]/@data-imgname')[0]
# names = [name[0:name.index('&')] for name in names.split('|')]
#发送请求
for i,n in enumerate(names):
resp = requests.get(f'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{ename}/{ename}-bigskin-{i+1}.jpg')
with open(f'{cname}/{n}.jpg','wb') as f:
f.write(resp.content)
print(f'已下载:{cname}的{n}皮肤')
sleep(2)