1. 程式人生 > 程式設計 >python 爬取英雄聯盟面板並下載的示例

python 爬取英雄聯盟面板並下載的示例

爬取結果:

python 爬取英雄聯盟面板並下載的示例

爬取程式碼

import os
import json
import requests
from tqdm import tqdm

def lol_spider():
  # 存放英雄資訊
  heros = []
  # 存放英雄面板
  hero_skins = []
  # 獲取所有英雄資訊
  url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js'
  hero_text = requests.get(url).text
  # 轉為 json 格式
  hero_json = json.loads(hero_text)['hero']
  path = os.getcwd()
  # 獲取當前資料夾路徑
  workspace = os.getcwd()
  # 面板路徑
  skin_path = "{}\\{}".format(workspace,'skins')
  # 遍歷列表
  for hero in hero_json:
    # 將每一個英雄的 id、name 放入一個字典中
    hero_dict = {'id': hero['heroId'],'name': hero['name']}
    # 放入列表
    heros.append(hero_dict)
  # 遍歷列表
  for hero in heros:
    hero_id = hero['id']
    hero_name = hero['name']
    # 為每一個英雄建立一個以自己名字命名的資料夾,用來存放面板圖片
    dir_name = skin_path + '\\{}'.format(hero_name)
    if not os.path.exists(dir_name):
      os.mkdir(dir_name)
    # 進入資料夾
    os.chdir(dir_name)
    # 根據每一個英雄的 id 生成面板資訊的 url
    hero_skin_url = 'https://game.gtimg.cn/images/lol/act/img/js/hero/' + hero_id + '.js'
    # 通過 url 獲取英雄的面板數量
    skin_text = requests.get(hero_skin_url).text
    skin_json = json.loads(skin_text)
    skin_list = skin_json['skins']
    # 獲取面板名
    hero_skins.clear()
    for skin in skin_list:
      hero_skins.append(skin['name'].replace('/','').replace('\\','').replace(' ',''))
    # 面板數量
    skins_num = len(hero_skins)
    s = ''
    for i in tqdm(range(skins_num),desc='【' + hero_name + '】面板下載'):
      if len(str(i)) == 1:
        s = '00' + str(i)
      elif len(str(i)) == 2:
        s = '0' + str(i)
      elif len(str(i)) == 3:
        pass
      try:
        # 拼接指定面板的 url
        skin_url = 'https://game.gtimg.cn/images/lol/act/img/skin/big' + hero_id + '' + s + '.jpg'
        img = requests.get(skin_url)
      except:
        # 沒有炫彩面板 url 則跳過
        continue
      # 儲存面板圖片
      if img.status_code == 200:
        with open(hero_skins[i] + '.jpg','wb') as f:
          f.write(img.content)



if __name__ == '__main__':
  lol_spider()

以上就是python 爬取英雄聯盟面板並下載的示例的詳細內容,更多關於python 爬取英雄聯盟面板的資料請關注我們其它相關文章!