Télécharger de la musique VKontakte

Bonne journée à tous.


Je voulais télécharger toute ma musique de VKontakte sur une clé USB, comme au bon vieux temps. Un peu sur Google et ne trouvant presque rien de plus ou moins acceptable, j'ai décidé d'agir par moi-même. Après une demi-heure, nous avons obtenu un script de travail pour nous-mêmes. Commençons donc.


Pour travailler, vous devez télécharger le vk_api et demander des modules!


Pour commencer, connectez les modules nécessaires et déclarez quelques variables:


import os import pickle import vk_api import requests from vk_api import audio from time import time vk_file = "vk_config.v2.json" REQUEST_STATUS_CODE = 200 path = 'vk_music/' 

Nous allons maintenant écrire la méthode d'autorisation sur votre compte VKontakte:


 def Auth(new=False): try: USERDATA_FILE = r"AppData/UserData.datab" #  ,   id global my_id #   ,         # ,     ?  ,   if (os.path.exists(USERDATA_FILE) and new == False): with open(USERDATA_FILE, 'rb') as DataFile: LoadedData = pickle.load(DataFile) login = LoadedData[0] password = LoadedData[1] my_id = LoadedData[2] else: #  ,     ,        if (os.path.exists(USERDATA_FILE) and new == True): os.remove(USERDATA_FILE) login = str(input(" \n> ")) password = str(input(" \n> ")) my_id = str(input(" id \n> ")) SaveUserData(login, password, my_id) SaveData = [login, password, my_id] with open(USERDATA_FILE, 'wb') as dataFile: pickle.dump(SaveData, dataFile) #    vk_session = vk_api.VkApi(login=login, password=password) try: vk_session.auth() #  ,   ,      .   . except: vk_session = vk_api.VkApi(login=login, password=password, auth_handler=auth_handler) # auth_handler=auth_handler -  , .  vk_session.auth() print('  .') vk = vk_session.get_api() global vk_audio #  ,       vk_audio = audio.VkAudio(vk_session) except KeyboardInterrupt: print('   .') 

La méthode vérifiera si nous nous sommes déjà connectés plus tôt? Si cela s'est produit, vous pouvez continuer dans ce compte ou vous reconnecter. Dans ce cas, les anciennes données seront effacées.


Ensuite, nous écrivons la méthode auth_handler, qui est nécessaire pour l'autorisation dans les comptes dans lesquels l'authentification à deux facteurs est activée:


 def auth_handler(): code = input("  \n> ") remember_device = True # True -         return code, remember_device 

Et donc, maintenant nous pouvons nous connecter à VKontakte. Dans la méthode Auth, la méthode SaveUserData () a été mentionnée, elle est nécessaire pour enregistrer les données. Écrivons-le:


 def SaveUserData(login, password, profile_id): USERDATA_FILE = r"AppData/UserData.datab" if (not os.path.exists("AppData")): #    AppData -   os.mkdir("AppData") SaveData = [login, password, profile_id] #     with open(USERDATA_FILE, 'wb') as dataFile: #      pickle.dump(SaveData, dataFile) 

Les données seront enregistrées sous forme binaire, afin de ne pas stocker le login et le mot de passe de l'utilisateur sous une forme claire.


Il reste à écrire une méthode pour télécharger de l'audio depuis VKontakte, faisons ceci:


 def main(): try: if (not os.path.exists("AppData")): os.mkdir("AppData") if not os.path.exists(path): os.makedirs(path) #  ,    -     auth_dialog = str(input(" ? yes/no\n> ")) if (auth_dialog == "yes"): Auth(new=True) elif (auth_dialog == "no"): Auth(new=False) else: print(',  .') main() print('  ...') os.chdir(path) #   audio = vk_audio.get(owner_id=my_id)[0] print(' :', len(vk_audio.get(owner_id=my_id)), '.') count = 0 time_start = time() print(" ...\n") #  , ,    . for i in vk_audio.get(owner_id=my_id): try: print(': ' + i["artist"] + " - " + i["title"]) count += 1 r = requests.get(audio["url"]) if r.status_code == REQUEST_STATUS_CODE: print(' : ' + i["artist"] + " - " + i["title"]) with open(i["artist"] + ' - ' + i["title"] + '.mp3', 'wb') as output_file: output_file.write(r.content) except OSError: print("!!!     â„–", count) time_finish = time() print("" + vk_audio.get(owner_id=my_id) + "   : ", time_finish - time_start + " .") except KeyboardInterrupt: print('   .') 

Eh bien, c'est tout. Nous avons maintenant un script de travail pour télécharger des enregistrements audio depuis VKontakte.
Voici Ă  quoi ressemble tout le code source:


Afficher le code source
 import os import pickle import vk_api import requests from vk_api import audio from time import time __version__ = 'VK Music Downloader v1.0' APP_MESSAGE = ''' _ . ___ /\\ | | | \\ | | | \\ / | / /__\\ | | | \\ | | | \\ / |/ / \\ |___| |__/ | |___| \\/ |\\ ''' vk_file = "vk_config.v2.json" REQUEST_STATUS_CODE = 200 path = 'vk_music/' def auth_handler(remember_device=None): code = input("  \n> ") if (remember_device == None): remember_device = True return code, remember_device def SaveUserData(login, password, profile_id): USERDATA_FILE = r"AppData/UserData.datab" SaveData = [login, password, profile_id] with open(USERDATA_FILE, 'wb') as dataFile: pickle.dump(SaveData, dataFile) def Auth(new=False): try: USERDATA_FILE = r"AppData/UserData.datab" #  ,   id global my_id if (os.path.exists(USERDATA_FILE) and new == False): with open(USERDATA_FILE, 'rb') as DataFile: LoadedData = pickle.load(DataFile) login = LoadedData[0] password = LoadedData[1] my_id = LoadedData[2] else: if (os.path.exists(USERDATA_FILE) and new == True): os.remove(USERDATA_FILE) login = str(input(" \n> ")) password = str(input(" \n> ")) my_id = str(input(" id \n> ")) SaveUserData(login, password, my_id) SaveData = [login, password, my_id] with open(USERDATA_FILE, 'wb') as dataFile: pickle.dump(SaveData, dataFile) vk_session = vk_api.VkApi(login=login, password=password) try: vk_session.auth() except: vk_session = vk_api.VkApi(login=login, password=password, auth_handler=auth_handler) vk_session.auth() print('  .') vk = vk_session.get_api() global vk_audio vk_audio = audio.VkAudio(vk_session) except KeyboardInterrupt: print('   .') def main(): try: if (not os.path.exists("AppData")): os.mkdir("AppData") if not os.path.exists(path): os.makedirs(path) auth_dialog = str(input(" ? yes/no\n> ")) if (auth_dialog == "yes"): Auth(new=True) elif (auth_dialog == "no"): Auth(new=False) else: print(',  .') main() print('  ...') os.chdir(path) #   audio = vk_audio.get(owner_id=my_id)[0] print(' :', len(vk_audio.get(owner_id=my_id)), '.') count = 0 time_start = time() #     print(" ...\n") #      for i in vk_audio.get(owner_id=my_id): try: print(': ' + i["artist"] + " - " + i["title"]) #         count += 1 r = requests.get(audio["url"]) if r.status_code == REQUEST_STATUS_CODE: print(' : ' + i["artist"] + " - " + i["title"]) with open(i["artist"] + ' - ' + i["title"] + '.mp3', 'wb') as output_file: output_file.write(r.content) except OSError: print("!!!     â„–", count) time_finish = time() print("" + vk_audio.get(owner_id=my_id) + "   : ", time_finish - time_start + " .") except KeyboardInterrupt: print('   .') if __name__ == '__main__': print(APP_MESSAGE) print(__version__ + "\n") main() 

J'Ă©tudie juste, donc je serai heureux de tous les commentaires dans le code. Merci de votre attention.

Source: https://habr.com/ru/post/fr468735/


All Articles