Created
May 26, 2021 05:10
-
-
Save a37h/1cbe71650c65bfa6c2995fe7e9b37e3a to your computer and use it in GitHub Desktop.
Download all audio tracks from your VK page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import requests | |
import pickle | |
import logging | |
import tqdm # pip install tqdm | |
import vk_api # pip install vk_api bs4 | |
from vk_api import audio | |
logging.basicConfig(filename='music.log', level=logging.DEBUG, | |
format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', datefmt='%d.%m.%Y %H:%M:%S') | |
logger = logging.getLogger(__file__) | |
PHONE = '' | |
PASSWORD = '' | |
TRACK_LIST_FILENAME = "track_list.pkl" | |
TRACKS_DIR = "tracks/" | |
# get track list | |
if os.path.exists(TRACK_LIST_FILENAME): | |
logger.info('Got tracks list from local file') | |
with open(TRACK_LIST_FILENAME, 'rb') as f: | |
track_list = pickle.load(f) | |
else: | |
logger.info('Loginning') | |
vk_session = vk_api.VkApi(login=PHONE, password=PASSWORD, auth_handler=lambda: (input('code:'), False)) | |
vk_session.auth() | |
logger.info('Getting page id') | |
page_id = vk_session.get_api().account.getProfileInfo()['id'] | |
logger.info('Getting tracks list via API') | |
print("Getting tracks list...") | |
track_list = audio.VkAudio(vk_session).get(owner_id=page_id) | |
with open(TRACK_LIST_FILENAME, 'wb') as f: | |
pickle.dump(track_list, f, 0) | |
# create tracks dir | |
if not os.path.isdir(TRACKS_DIR): | |
os.mkdir(TRACKS_DIR) | |
# download tracks | |
logger.info('Starting tracks download') | |
print("Downloading tracks...") | |
for i in tqdm.tqdm(track_list): | |
try: | |
track_fname = i["artist"].replace('_', '-') + '_' + i["title"].replace('_', '-') + '.mp3' | |
track_fname = track_fname.replace('/', '-') | |
track_path = TRACKS_DIR + track_fname | |
if os.path.exists(track_path): | |
logger.info(f'Already dowloaded {track_fname}') | |
continue | |
r = requests.get(i["url"]) | |
if r.status_code == 200: | |
with open(track_path, 'wb') as track_f: | |
logger.info(f'Successfully downloaded {track_fname}') | |
track_f.write(r.content) | |
else: | |
logger.error(f"Couldn't download {track_fname} - got status code {r.status_code}") | |
except Exception as e: | |
logger.error(f"Couldn't download {track_fname} - exception occured") | |
logger.exception(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment