Day 46 - create Spotify playlist


Posted by pei_______ on 2022-05-27

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


(Python package) spotipy 2.19.0

spotipy 2.19.0 Documentation


# constant

import requests
import spotipy
from bs4 import BeautifulSoup
from spotipy.oauth2 import SpotifyOAuth
from spotipy.oauth2 import SpotifyClientCredentials
import pprint

URL = "https://www.billboard.com/charts/hot-100/2000-08-12/"

SPOTIFY_CLIENT_ID = YOUR OWN CLIENT ID
SPOTIFY_CLIENT_SECRET = YOUR OWN CLIENT SECRET
SPOTIFY_URL = "http://example.com"
ACCESS_TOKEN = YOUR OWN ACCESS TOKEN
scope = "playlist-modify-private"
PLAYLIST_ID = YOUR OWN PLAYLIST ID
# scarbe 100 Songs's title from wesite

response = requests.get(url=URL)
html_content = response.text

soup = BeautifulSoup(html_content, "html.parser")
song_codes = soup.find_all(name="h3", id="title-of-a-story", class_="a-no-trucate")
# get access token

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope,
client_id=SPOTIFY_CLIENT_ID,
client_secret=SPOTIFY_CLIENT_SECRET, redirect_uri=SPOTIFY_URL))
results = sp.current_user_saved_tracks()

for idx, item in enumerate(results['items']):
    track = item['track']
    print(idx, track['artists'][0]['name'], " – ", track['name'])
# get user id

client = spotipy.client.Spotify(auth=ACCESS_TOKEN)
user_id = client.current_user()["id"]
print(user_id)
# create a new playlist

sp.user_playlist_create(user=user_id, name="Billboard 100", public=False)
# search song's url & add to tha playlist

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id=SPOTIFY_CLIENT_ID,client_secret=SPOTIFY_CLIENT_SECRET))

song_urls = []

for song in song_codes:
    song_title = song.get_text()[14:].split("\t")[0]
    track_url = sp.search(song_title)["tracks"]["items"][0]['external_urls']['spotify']
    song_urls.append(track_url)

sp.playlist_add_items(playlist_id=PLAYLIST_ID, items=song_urls)

#Python #課堂筆記 #100 Days of Code







Related Posts

物件導向--基於類別與原型的範例

物件導向--基於類別與原型的範例

Day 139

Day 139

C 語言練習程式(1) & linux把檔案內容複製到剪貼簿

C 語言練習程式(1) & linux把檔案內容複製到剪貼簿


Comments