爬虫学习笔记-requests爬取王者荣耀皮肤图片

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)
相关推荐
齐生13 天前
iOS 知识点 - 渲染机制、动画、卡顿小集合
笔记
用户962377954484 天前
VulnHub DC-1 靶机渗透测试笔记
笔记·测试
齐生15 天前
iOS 知识点 - IAP 是怎样的?
笔记
tingshuo29175 天前
D006 【模板】并查集
笔记
tingshuo29176 天前
S001 【模板】从前缀函数到KMP应用 字符串匹配 字符串周期
笔记
西岸行者11 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky11 天前
Django入门笔记
笔记·django
勇气要爆发11 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意11 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发11 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain