Descargar musica VKontakte

Buen dia a todos.


Quería descargar toda mi música de VKontakte a una unidad flash USB, como en los viejos tiempos. Buscando un poco en Google y sin encontrar casi nada más o menos aceptable, decidí actuar por mi cuenta. Después de media hora, obtuvimos un guión de trabajo para nosotros. Entonces comencemos.


Para trabajar, debe descargar vk_api y solicitar módulos.


Para comenzar, conecte los módulos necesarios y declare algunas 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/' 

Ahora escribiremos el método de autorización en su cuenta de 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('   .') 

¿El método verificará si ya iniciamos sesión anteriormente? Si esto sucedió, puede continuar en esta cuenta o iniciar sesión nuevamente. En este caso, los datos antiguos se borrarán.


A continuación, escribimos el método auth_handler, que es necesario para la autorización en cuentas en las que se habilita la autenticación de dos factores:


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

Y así, ahora podemos iniciar sesión en VKontakte. En el método Auth, se mencionó el método SaveUserData (), es necesario para guardar datos. Escribámoslo:


 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) 

Los datos se registrarán en forma binaria, para no almacenar el inicio de sesión y la contraseña del usuario en forma clara.


Queda por escribir un método para descargar audio de VKontakte, hagamos esto:


 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('   .') 

Bueno, eso es todo. Ahora tenemos un script de trabajo para descargar grabaciones de audio de VKontakte.
Así es como se ve todo el código fuente:


Mostrar código fuente
 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() 

Solo estoy estudiando, así que estaré contento con todos los comentarios en el código. Gracias por su atencion

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


All Articles