本章由 玉米 分享,筆記連結網址於此,由 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']
此方法與步驟二第一個區塊的程式碼是一樣的
步驟三:
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)
若是在步驟二的時候 → scope=“playlist-modify-private”,這裡public參數要設為False
補充
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 讓使用者可以授權第三方網站存取他們儲存在另外服務提供者的某些特定資訊,而非所有內容。(資料來源連結)