Day 46 - Intermediate+ Create a Spotify Playlist using the Musical Time Machine

本章由 玉米 分享,筆記連結網址於此,由 Sky 取得同意後,整理如下。

時間:2021年6月27日 20:30~21:00
與會人員:玉米, Shadow, Dot, Wayne, Yeh, Sky
分享:玉米

目標:

創建Spotify播放清單,清單內容為過去某一天的billboard前百大熱門歌曲


步驟前:

輸入想要獲取過去哪一天的音樂 (日期格式:YYYY-MM-DD)

以下程式碼有做簡單的正則式,以輸入期望格式

is_continue = True
while is_continue:
    answer = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD:\n")
    pattern = r'[0-9]{4}-[0-9]{2}-[0-9]{2}'
    if re.match(pattern, answer) is not None:
        is_continue = False

year = answer.split("-")[0]

步驟一:

Scraping Billboard Song List

full_url = URL + str(answer)
response = requests.get(url=full_url).text
soup = BeautifulSoup(response, 'html.parser')
songs = soup.find_all(name="span", class_="chart-element__information__song")
song_lst = [song.getText() for song in songs]

步驟二:

Authorized Spotify to get user id (在最下面有分享一些 補充 可以看一下)

credentials = SpotifyOAuth(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        redirect_uri="https://example.com/",
        scope="playlist-modify-private",
        cache_path="token.txt")

token = credentials.get_access_token()['access_token']
sp = spotipy.Spotify(auth=token)
user_id = sp.current_user()['id']
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID,
                                               client_secret=CLIENT_SECRET,
                                               redirect_uri="https://example.com/",
                                               scope="playlist-modify-private",
                                               cache_path="test_token.txt"))
user_id = sp.current_user()['id']

:point_up: 此方法與步驟二第一個區塊的程式碼是一樣的

步驟三:

Search the song in Spotify and Save to empty list

song_id_lst = []
for song in song_lst:
    result = sp.search(q=f"track:{song} year:{year}", type="track")
    try:
        sond_track_id = result['tracks']['items'][0]['uri']
        song_id_lst.append(sond_track_id)
    except:
        print(f"{song} doesn't exist in Spotify.")

步驟四:

Create Playlist And Add the Songs into it

#------------create playlist--------------#
PLAYLIST_NAME = f"{answer} Billboard 100"
playlist = sp.user_playlist_create(user=user_id, name=PLAYLIST_NAME, public=False)

#------------add song to playlist--------------#
sp.playlist_add_items(playlist_id=playlist['id'], items=song_id_lst)

:secret: 若是在步驟二的時候 → scope=“playlist-modify-private”,這裡public參數要設為False :secret:

Day46-4

補充

SpotifyClientCredentials → Without user authentication (用以查詢,無法獲取 user_id)

SpotifyOAuth → With user authentication

下面為 SpotifyClientCredentials 使用方式範例:

Auth = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
print(Auth.get_access_token())
sp = spotipy.Spotify(auth_manager=Auth)

OAuth補充

OAuth 允許使用者提供一個權杖,而不是使用者名稱和密碼來存取他們存放在特定服務提供者的資料。每一個權杖授權一個特定的網站(例如,影片編輯網站)在特定的時段(例如,接下來的 2 小時內)內存取特定的資源(例如僅僅是某一相簿中的影片)。這樣,OAuth 讓使用者可以授權第三方網站存取他們儲存在另外服務提供者的某些特定資訊,而非所有內容。(資料來源連結)

OAuth老師提供參考連結

Day 46 好難…
跟著老師的步驟 做到第三步就行不通了,
看這邊的上課筆記,複製貼上,但還是一直遭遇到問題,花了一整天還是搞不懂,Help~~~
下面是用 pycharm 跑出來的問題訊息

C:\Users\jeff\Web Development\Musical_Time_ Machine\main.py:33: DeprecationWarning: You’re using ‘as_dict = True’.get_access_token will return the token string directly in future versions. Please adjust your code accordingly, or use get_cached_token instead.
token = credentials.get_access_token()[‘access_token’]

不好意思,可能要麻煩你再貼更詳細的code相關資訊才能幫你找到問題大概在哪喔~不過你可以看看是不是token過期或是token檔案位置有沒有錯?!
還有根據紅色的錯誤提示你可以看一下你的第33行 :pray:

2個讚

抱歉,後來這天的課程因為太難搞不懂,所以最後我放棄直接跳到下一天了,
所以沒注意到您願意協助的留言,謝謝你~

您提到token 過期或是位置放錯,我不敢確定,但token是寫程式同一天產生的,位置在同一層,我截圖如下,另外,我的程式碼放在下面,如果您有空,再請您幫我看看,非常感謝您的協助。

我的程式碼如下 :

from bs4 import BeautifulSoup
import requests
import re
import spotipy
from spotipy.oauth2 import SpotifyOAuth

CLIENT_ID = “ffb280f58c1b4f818acdf71778ed94fd” ## Client ID
CLIENT_SECRET = “d507980488d544399b89284728293457” ## Client Secret
URL = “The Hot 100 Chart | Billboard

is_continue = True
while is_continue:
answer = input(“Which year do you want to travel to? Type the date in this format YYYY-MM-DD:\n”)
pattern = r’[0-9]{4}-[0-9]{2}-[0-9]{2}’
if re.match(pattern, answer) is not None:
is_continue = False

year = answer.split("-")[0]

full_url = URL + str(answer)
response = requests.get(url=full_url).text
soup = BeautifulSoup(response, ‘html.parser’)
songs = soup.find_all(name=“span”, class_=“chart-element__information__song”)
song_lst = [song.getText() for song in songs]

credentials = SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=“http://127.0.0.1:5500/”,
scope=“playlist-modify-private”,
cache_path=“token.txt”)

token = credentials.get_access_token()[‘access_token’]
sp = spotipy.Spotify(auth=token)
user_id = sp.current_user()[‘id’]

song_id_lst = []
for song in song_lst:
result = sp.search(q=f"track:{song} year:{year}", type=“track”)
try:
sond_track_id = result[‘tracks’][‘items’][0][‘uri’]
song_id_lst.append(sond_track_id)
except:
print(f"{song} doesn’t exist in Spotify.")

#------------create playlist--------------#
PLAYLIST_NAME = f"{answer} Billboard 100"
playlist = sp.user_playlist_create(user=user_id, name=PLAYLIST_NAME, public=False)

#------------add song to playlist--------------#
sp.playlist_add_items(playlist_id=playlist[‘id’], items=song_id_lst)

未命名

token.txt 內容如下 :

{“access_token”: “BQBJbPk7SRErhDaEhvAEeihLG5RRSAqOqNlYP1qApjW9S2mC5KfDvLQ0k2M3TKJJr5Xme5lyu3Qy7M0OfCqpUzM2MPNdGLTLnycM4X6kT23Y4oy_K8NhpG7Hwd2Hya61J6cAKE_3cPBKjVv7cB5t-CU_gAeIdFXcdnzc4aJ7x2W9tMezOymr4oqpODDg1AnapA”, “token_type”: “Bearer”, “expires_in”: 3600, “scope”: “playlist-modify-private”, “expires_at”: 1634220003, “refresh_token”: “AQBDTgLSKh-niZW6e6OsH3lnDYRXLrBvm4yY5OzzPkoY2Jm95k5IgsO95–cpElRb-QTpXRqpxQDxpUZwurMKa0UvEeVSNMhQMxUK8LJEOaP9QRkCayI6cC_pPuHGA8LijA”}

1個讚