-
-
Save TheMuellenator/c84616c21f0f9ce68c12c357d3e1c794 to your computer and use it in GitHub Desktop.
| sp = spotipy.Spotify( | |
| auth_manager=SpotifyOAuth( | |
| scope="playlist-modify-private", | |
| redirect_uri="http://example.com", | |
| client_id=YOUR UNIQUE CLIENT ID, | |
| client_secret= YOUR UNIQUE CLIENT SECRET, | |
| show_dialog=True, | |
| cache_path="token.txt" | |
| ) | |
| ) | |
| user_id = sp.current_user()["id"] | |
| date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ") | |
| song_uris = ["The list of", "song URIs", "you got by", "searching Spotify"] | |
| playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False) | |
| # print(playlist) | |
| sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris) |
Hello Developers,
import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import json
Note: Set Up a Spotify Developer Account
Go to the Spotify Developer Dashboard.
Log in and create a new app.
Note down the Client ID and Client Secret.
Set the Redirect URI (e.g., http://localhost:8888/callback or https://example.com).
Constants
CLIENT_ID = "YOUR_CLIENT_ID"
CLIENT_SECRET = "YOUR_CLIENT_SECRET"
REDIRECT_URI = "https://example.com" # I used this.
SPOTIFY_SCOPE = "playlist-modify-private"
date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")
URL = f"https://billboard.com/charts/hot-100/{date}/" # Dynamic URL
URL = "https://www.billboard.com/charts/hot-100/2000-08-12" # Constant URL for the testing
header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0"}
response = requests.get(url = URL, headers=header)
website_data = response.text
soup = BeautifulSoup(website_data, "html.parser")
Get the Song name of top 100 list
song_names = [name.getText().strip() for name in soup.select("li ul li h3")]
print(song_names)
Authenticate
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SPOTIFY_SCOPE))
user-library-read
user_id = sp.current_user()["id"]
print(user_id)
Create Playlist
playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False, description=f"{date} Billboard 100")
print(playlist)
Get the song uri to add into the playlist tracks
song_uris = []
for song in song_names:
result = sp.search(q=song) # type = dictionary to get data.
try:
# print(json.dumps(result, sort_keys=4, indent=4)) # this is to identify the song url
uri = result["tracks"]["items"][0]["uri"]
song_uris.append(uri)
except IndexError:
print(f"{song} doesn't exist in Spotify. Skipped.")
Add songs into playlist
sp.playlist_add_items(playlist_id=playlist['id'], items=song_uris)
print("Tracks added to the playlist!")
It feels too difficult for me right now. :(
I find it hard to fully understand the Spotify library documentation.
However, I will try to follow the example code you provided, and later I will give it another attempt.
Yes, the documentation is vast, and it's not readily available to understand the concepts.
Please post your question on the code I posted. I can try to clarify the same to you.
Thanks!
I'm so happy that I was able to finish this project. There might be some problems on the solution due to some system update but glad that I was able to solve it through the help of the people here. Thank you so much.
The solutions I did are:
- The redirect URI should be "https://open.spotify.com/" not "'https://example.com/", and should also match the redirect URI on your Dashboard App URI
- I changed the scope from "playlist-modify-private" to "playlist-modify-private playlist-modify-public". There should be two scopes added.
- When the "Enter the URL you are directed:" pop up on your console, copy the whole URL to which you are directed. It won't appear the second time you run your code again.
Here's my code. Hope it helps:
import export
import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")
url = f'https://www.billboard.com/charts/hot-100/{date}/'
headers = {'user-agent': 'your own user agent'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text,'html.parser')
song_names_spans = soup.select("li ul li h3")
song_names = [song.getText().strip() for song in song_names_spans]
print(song_names)
REDIRECT_URI = "https://open.spotify.com/"
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
cache_path="token.txt",
scope="playlist-modify-private playlist-modify-public"))
year_input = date.split("-")[0]
song_uris = []
for song in song_names:
search_requests = sp.search(q=f"track:{song} year:{year_input}")
try:
uri = search_requests["tracks"]["items"][0]["uri"]
song_uris.append(uri)
except IndexError:
print(f"\n{song} does not exist in Spotify. Skipped...\n")
user_id = sp.current_user()["id"]
playlist = sp.user_playlist_create(user=user_id,
name=f"{date} Billboard 100",
public=False,
description=f"Top 100 songs on {date}")
sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris)
Good to hear, ChaVarilla!
Happy Learning!
As of October 2025, this code is working as attended for everyone reference
import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os
from dotenv import load_dotenv
load_dotenv()
user_input = input('Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ')
headers = {'User-Agent': 'MY USER AGENT'}
site_html = requests.get(f'https://www.billboard.com/charts/hot-100/{user_input}/', headers=headers).text
soup = BeautifulSoup(site_html, features='html.parser')
top_100 = soup.select('li ul li h3')
top_100_list = [songs.text.strip().replace('\n', '').replace('\t', '') for songs in top_100]
#print(top_100_list)
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id=os.getenv('SPOTIFY_CLIENT_ID'),
client_secret=os.getenv('SPOTIFY_CLIENT_SECRET'),
scope='playlist-modify-private',
cache_path='token.txt',
redirect_uri='http://127.0.0.1:9090',
show_dialog=True,
username='g35k',
))
user_id = sp.current_user()["id"]
song_uris = []
year = user_input.split('-')[0]
print(year)
for song in top_100_list:
result = sp.search(q=f'track:{song} year:{year}', type='track')
print(result)
try:
uri=result['tracks']['items'][0]['uri']
song_uris.append(uri)
except IndexError:
print(f'{song} not found')
playlist = sp.user_playlist_create(user=user_id, name=f'{user_input} Billboard 100', public=False)
sp.playlist_add_items(playlist_id=playlist['id'], `items=song_uris)```
I believe struggling to understand the API document is a benefit, Learning happen best when struggling lol.
It took a bit because the documentation isn't the greatest for Spotipy, but after doing everything based on Spotify API, I used the Spotipy package and got it solved.