創建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.")