当前位置:网站首页>Here comes the hero League full skin Downloader

Here comes the hero League full skin Downloader

2022-06-26 17:08:00 Python concentration camp

This is the hero skin of the part downloaded through the hero alliance downloader written by the blogger , You can see the effect . Each hero's skin will automatically create a corresponding folder according to the hero's name .

【 Read the whole passage 】

Please read the complete source code at the end of the article ...

file

file

file

The implementation idea is relatively simple , Also through PyQt5 To write the download page . Finally through request Module to write the download part of the skin . The operation process is as follows , Select the storage path of the skin . Then click directly to start downloading , And you can view the download progress information in the text browser .

file

Next , The main implementation part of the code block is introduced . First , Introduce which third-party modules are used in the whole code block .

#  Hero alliance skin download related dependent modules 

import requests  #  Network request Library 
import re  #  Regular expression matching Library 
import json  # JSON Format conversion library 
import os  #  Application operation Library 
import time  #  Time module 
from random import random  #  Random number module 
from fake_useragent import UserAgent  # user_agent  Build a library 
import logging  #  Log module 
import sys  #  system operation 

# pyqt5 The module reference of is not introduced here , It's been used recently .

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

UI The design process of interface, code block and the application process of signal and slot function .

def init_ui(self):
        self.setWindowTitle(' Hero skin Downloader    official account :[Python  concentration camp ]')
        self.setWindowIcon(QIcon('lol.ico'))
        self.resize(500,250)

        vbox = QVBoxLayout()

        self.save_dir = QLineEdit()
        self.save_dir.setReadOnly(True)

        self.save_btn = QPushButton()
        self.save_btn.setText(' route ')
        self.save_btn.clicked.connect(self.save_btn_click)

        self.thread_ = DownLoadThread(self)
        self.thread_.trigger.connect(self.update_log)

        self.start_btn = QPushButton()
        self.start_btn.setText(' Start the download ')
        self.start_btn.clicked.connect(self.start_btn_click)

        grid = QGridLayout()
        grid.addWidget(self.save_dir, 0, 0, 1, 2)
        grid.addWidget(self.save_btn, 0, 2, 1, 1)
        grid.addWidget(self.start_btn, 0, 3, 1, 1)

        self.result_brower = QTextBrowser()
        self.result_brower.setFont(QFont(' Song style ', 8))
        self.result_brower.setReadOnly(True)
        self.result_brower.setPlaceholderText(' Hero skin batch download progress display area ...')
        self.result_brower.ensureCursorVisible()

        vbox.addWidget(self.result_brower)
        vbox.addLayout(grid)

        self.setLayout(vbox)

    def start_btn_click(self):
        self.start_btn.setEnabled(False)
        self.thread_.start()

    def update_log(self, text):
        cursor = self.result_brower.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.result_brower.append(text)
        self.result_brower.setTextCursor(cursor)
        self.result_brower.ensureCursorVisible()

    def save_btn_click(self):
        directory = QFileDialog.getExistingDirectory(self, " Select a folder ", self.cwd)
        self.save_dir.setText(directory)

UI Interface design code , Follow and others PyQt5 Same design paradigm . Written according to this paradigm UI Personally, the code block looks more beautiful .

In order to prevent the slow download process from causing UI The main thread of the interface hangs directly , Therefore, it needs to be used separately when writing the logic of download business QThread It is written in the way of sub thread . This can separate the business logic from the main page logic , There will be no hanging up .

class DownLoadThread(QThread):

    trigger = pyqtSignal(str)

    def __init__(self, parent=None):
        super(DownLoadThread, self).__init__(parent)
        #  Initialize log object 
        self.logger = logging.getLogger(' Hero League skin ')
        logging.basicConfig()
        self.logger.setLevel(logging.DEBUG)
        self.parent = parent
        self.working = True

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):

        '''
         Hero alliance skin download function 
        :return:
        '''
        while self.working == True:
            #  structure useragent Identity device information 
            headers = {
                "User-Agent": str(UserAgent().random),
            }

            self.logger.info(' Generation of identity device information completed ')
            self.trigger.emit(' Generation of identity device information completed !')

            #  stay LOL The official website of has been analyzed champion.js It contains the heroes we want to use ID Number , therefore , Put this JS Download the file 
            champion_js_url = "https://lol.qq.com/biz/hero/champion.js"

            #  send out http request 、 The request address is this JS File address . Will download it .
            response = requests.get(url=champion_js_url, headers=headers)

            self.logger.info('champion.js  File download complete ')
            self.trigger.emit('champion.js  File download complete !')

            #  Get downloaded text information 
            text = response.text
            self.logger.info('champion.js  Text information :' + text)

            #  matching champion The object corresponds to JSON data , The JSON The number of data 0 One location contains heroes ID Numbered JSON data 
            hero_json = re.findall(r'champion=(.*?);', text, re.S)[0]

            #  take JSON Data to dict Dictionaries 
            hero_dict = json.loads(hero_json)
            self.logger.info(' hero ID Dictionary information :' + str(hero_dict))

            #  Hero by hero information traversal 
            for hero_data in hero_dict["data"].items():

                #  To get hero details JS file 
                hero_js_url = "http://lol.qq.com/biz/hero/{}.js"

                #  Send a request to download the JS file 、hero_data[0] Take the first place 0 One is a hero ID
                response = requests.get(url=hero_js_url.format(hero_data[0]), headers=headers)

                #  Get Download Text 
                text = response.text
                self.logger.info(hero_data[0] + '.js  Text information :' + text)
                self.trigger.emit(hero_data[0] + '.js  File download complete !')

                skins_dict = json.loads(re.findall("{}=(.*?);".format(hero_data[0]), text, re.S)[0])
                self.logger.info(' Current hero skin dictionary :' + str(skins_dict))

                #  From the dictionary  skins_dict  Get skin list 
                skins_list = skins_dict["data"]["skins"]

                #  Get hero name 
                hero_name = hero_data[1]["name"]

                #  Create under current directory images Folder 、 Take the hero name as the folder name 
                os.makedirs(r"./images/{}".format(hero_name), exist_ok=True)

                for skin_info in skins_list:

                    #  Initialize skin picture address 
                    skin_pic_url = "https://ossweb-img.qq.com/images/lol/web201310/skin/big{}.jpg"

                    #  Send download request 
                    reponse = requests.get(url=skin_pic_url.format(skin_info["id"]), headers=headers)

                    try:
                        self.logger.info(' Save the path ' + self.parent.save_dir.text().strip())

                        #  Save skin 
                        with open(r"" + self.parent.save_dir.text().strip() + "/{}/{}.jpg".format(hero_name,
                                                                                                 skin_info["name"]),
                                  "wb") as f:
                            f.write(reponse.content)

                        self.logger.info("{}  Download complete !".format(skin_info["name"]))
                        self.trigger.emit("{}  Download complete !".format(skin_info["name"]))

                    except:
                        self.logger.error(skin_info["name"] + ', Download exception . Skip next !')
                        self.trigger.emit(skin_info["name"] + ', Download exception . Skip next !')

            self.sleep(round(random(), 5))

Because there are many businesses to download this piece , For your convenience . Basically, I wrote comments on the main code blocks , Small partners in need can be transformed according to their own needs .

Reply in official account " Hero League skin Downloader " Get the full source code ...

file

I am a [Python concentration camp ]、 I'm glad you saw the last , I am a person who focuses on Python Official account of knowledge sharing , I hope I can get your attention ~

【 Past highlights 】

PyQt5 Production of sensitive word detection tool based on , The gospel of the operator ...

Hand drawn picture generator : Shuey Rhon Rhon as an example, one button generation ...

The mascot of the Winter Olympic Games just released : Ice mound , Source code attached ...

The most beautiful form viewing plug-in :tabulate

Tiktok system in the same class ,PyQt5 It's easy to write ...

原网站

版权声明
本文为[Python concentration camp]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202162111104266.html

随机推荐