Python爬虫案例—爬取王者荣耀皮肤图

#导入相关库
import re
import requests
from bs4 import BeautifulSoup
import os
import urllib3 
# 禁用 InsecureRequestWarning 警告,防止报错误
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 建立保存路径
path = r'd:\王者荣耀壁纸'

# 下载函数
def download(url, path, name, hero_name):
    hero_dir = os.path.join(path, hero_name)
    if not os.path.exists(hero_dir):
        os.makedirs(hero_dir)
    try:
        response = requests.get(url, verify=False)
        response.raise_for_status()   #报错4xx——5xx时报错
        with open(os.path.join(hero_dir, f"{name}.jpg"), "wb") as f:
            f.write(response.content)
            print(f"已下载 《{name}》 图片")
    except requests.RequestException as e:
        print(f"下载图片失败:{e}")

# 单个英雄的所有皮肤图片URL、名字、编号
def get_single_hero_list(hero_id, hero_name, id_name):
    hero_url = f"https://pvp.qq.com/web201605/herodetail/{id_name}.shtml"
    try:
        response = requests.get(hero_url, verify=False)
        response.raise_for_status()#报错4xx——5xx时报错
        response.encoding = "gbk"      #转码
        soup = BeautifulSoup(response.text, "html.parser")
        name_data = soup.find("ul", class_="pic-pf-list pic-pf-list3").get("data-imgname")
        name_list = re.sub(r'&\d+', '', name_data)  # 使用r前缀修正正则表达式
        hero_name_list = name_list.split("|")

        for num, name in enumerate(hero_name_list):  #枚举法:数字和皮肤名字同时提取
            num += 1
            url = f"https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{hero_id}/{hero_id}-bigskin-{num}.jpg"
            download(url, path, name, hero_name)
    except requests.RequestException as e:
        print(f"获取英雄详情失败:{e}")
    except AttributeError as e:
        print(f"解析英雄详情页面失败:{e}")

# 获取所有英雄目录
def get_main():
    hero_list_url = "https://pvp.qq.com/web201605/js/herolist.json"
    try:
        response = requests.get(hero_list_url, verify=False)
        response.raise_for_status()  #报错4xx——5xx时报错
        heroes = response.json()

        for hero in heroes:
            hero_id = hero["ename"]
            hero_name = hero["cname"]
            id_name = hero.get("id_name", hero_id) # 如果没有"id_name",使用"ename"
            get_single_hero_list(hero_id, hero_name, id_name)
    except requests.RequestException as e:
        print(f"获取英雄列表失败:{e}")

if __name__ == '__main__':
    get_main()
    print("下载完成")

#读取顺序为:

# 1 :if __name__ == '__main__':

# 2 :获取所有英雄目录

# 3 :单个英雄的所有皮肤图片URL、名字、编号

# 4 :下载函数

#该页面在下载好库后,在d盘下建立一个 王者荣耀壁纸 文件即可全部复制粘贴运用

提示!本文章仅供学习交流,严禁用于任何商业和非法用途,如有侵权,可联系本文作者删除!

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫可以用于抓取王者荣耀皮肤信息,通常通过网络请求库如requests和BeautifulSoup、Scrapy等工具,配合HTML解析技术来实现。以下是基本步骤: 1. **确定目标网站**:首先需要访问王者荣耀皮肤展示页面的URL,比如腾讯官网或其他第三方游戏资讯网站。 2. **发送HTTP请求**:使用requests库发送GET请求获取网页源代码。 3. **解析HTML**:利用BeautifulSoup库分析响应内容,找到包含皮肤名称、片链接等数据的部分。 4. **提取信息**:提取出皮肤名称、价格、片地址等所需的数据。 5. **保存数据**:将数据存储到本地文件(如CSV或JSON),或者直接插入数据库,便于后续处理和查询。 6. **处理反爬机制**:注意检查并遵守网站的robots.txt规则,以及可能存在的验证码、动态加载等内容。 **示例代码片段**(简化版,实际操作需考虑异常处理和更复杂的解析): ```python import requests from bs4 import BeautifulSoup url = "https://example.com/kingofglory/skins" # 替换为你想要爬取的网址 response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 查找皮肤元素并提取数据 skins_data = [] for skin_element in soup.find_all('div', class_='skin-item'): # 类名假设为'skin-item' name = skin_element.find('h3').text image_url = skin_element.find('img')['src'] skins_data.append({ 'name': name, 'image_url': image_url, # ... 其他可能的数据 }) # 保存数据 with open('skins.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=skins_data.keys()) writer.writeheader() writer.writerows(skins_data)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值