Created
January 26, 2020 19:30
-
-
Save mitchellvitez/9f24ecc2c769f85712577d74e4711085 to your computer and use it in GitHub Desktop.
download all spotify links from a website into a playlist
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 bs4 | |
import httplib2 | |
import spotipy | |
import sys | |
import time | |
url = 'http://example.com/music' # full url of a site with spotify links on it | |
username = 'username' # your spotify username | |
playlist_id = 'abcdef1234567890' # id of the playlist you want tracks to fill | |
# https://developer.spotify.com/dashboard to get a token | |
token = spotipy.util.prompt_for_user_token(username, 'playlist-modify-public') | |
if not token: | |
print('invalid token') | |
sys.exit() | |
# grab all track ids from site | |
status, response = httplib2.Http().request(url) | |
tracks = [] | |
for link in bs4.BeautifulSoup(response, parse_only=bs4.SoupStrainer('a'), features='html.parser'): | |
if link.has_attr('href'): | |
href = link.get('href') | |
if href.startswith('https://open.spotify'): | |
tracks.append(href.split('/')[-1]) | |
# add tracks to playlist | |
# normally would pool http requests but spotify rate limits you anyways | |
sp = spotipy.Spotify(auth=token) | |
sp.trace = False | |
for track in tracks: | |
print('downloading', track) | |
try: | |
results = sp.user_playlist_add_tracks(username, playlist_id, [track]) | |
except: | |
try: | |
# if id isn't a track, check if it's an album and download all tracks | |
track_ids = [item['id'] for item in sp.album_tracks(track)['items']] | |
results = sp.user_playlist_add_tracks(username, playlist_id, track_ids) | |
except Exception as e: | |
print(track, e) | |
# can probably get away with a faster rate | |
time.sleep(0.25) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment