-
-
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) |
from bs4 import BeautifulSoup
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# Replace these with your actual Spotify API credentials
CLIENT_ID = "your_client_id"
SECRET_KEY = "your_secret_key"
REDIRECT_URI = "http://example.com" # Use your desired redirect URI
# Scraping Billboard 100
date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")
response = requests.get(f"https://www.billboard.com/charts/hot-100/{date}")
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]
# Spotify Authentication
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
scope="playlist-modify-private",
redirect_uri=REDIRECT_URI,
client_id=CLIENT_ID,
client_secret=SECRET_KEY,
show_dialog=True,
cache_path="token.txt"
)
)
user_id = sp.current_user()["id"]
# Searching Spotify for songs by title
song_uris = []
year = date.split("-")[0]
for song in song_names:
result = sp.search(q=f"track:{song} year:{year}", type="track")
if result["tracks"]["items"]:
uri = result["tracks"]["items"][0]["uri"]
song_uris.append(uri)
else:
print(f"{song} doesn't exist in Spotify. Skipped.")
# Creating a new private playlist in Spotify
playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False)
print(f"Playlist created: {playlist['name']}")
print(playlist)
# Adding songs found into the new playlist
sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris)
print(f"{len(song_uris)} songs added to the playlist.")
****
export CLIENT_ID='your-spotify-client-id'
export CLIENT_SECRET='your-spotify-client-secret'
export REDIRECT_URI='your-app-redirect-url'
****
As non native speaker I'm struggling everyday, feeling stupid anytime sit at front of computer. Spend 400 days just to learn 50% of the course... But I guess that's the path I must take.
This lesson alone took me more than 10 days just to understand the solution lol.
So I made a video step by step how to write the code based on the solution. Hope this will save some time for anyone who not really good at English like me.
https://www.youtube.com/watch?v=Oxph5K23_5w
After Executing the above code , i am getting below error
urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091)
If you're done but yet your playlist doesn't reflect try using http://localhost:8888/callback as your Redirect url in both your code and your spotify developer setting
REDIRECT_URI = "http://localhost:8888/callback"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope="playlist-modify-private"
))
Step 4: Get the current user ID
user = sp.current_user()
user_id = user['id']
Step 5: Create a new Spotify playlist
playlist_name = f"Billboard Hot 100 - {date}"
playlist_description = f"Top 100 songs on Billboard for {date}"
new_playlist = sp.user_playlist_create(user=user_id, name=playlist_name, description=playlist_description, public=False)
print(f"Created Playlist: {new_playlist['name']} (ID: {new_playlist['id']})")
Step 6: Search for each song on Spotify and add to the playlist
track_uris = []
for song in song_titles:
result = sp.search(q=f"track:{song}", type="track", limit=1)
try:
track_uri = result['tracks']['items'][0]['uri']
track_uris.append(track_uri)
except IndexError:
print(f"{song} not found on Spotify. Skipping.")
Add all found tracks to the playlist
if track_uris:
sp.playlist_add_items(playlist_id=new_playlist['id'], items=track_uris)
print(f"Added {len(track_uris)} songs to the playlist.")
else:
print("No songs were added to the playlist.")
This is my version and it works for me having as an end result adding a playlist to my Spotify account.
mport spotipy
from spotipy.oauth2 import SpotifyOAuth
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
import os
import pprint
Top 100 songs travel to memory lane
year_to_travel = input("What year would you like to travel? Please type the date on this format YYYY-MM-DD\n")
url = f"https://www.billboard.com/charts/hot-100/{year_to_travel}"
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0"
}
response = requests.get(url=url, headers=header)
soup = BeautifulSoup(response.content, "html.parser")
print(soup.prettify())
with open("page_to_check.html", "w", encoding='utf-8') as file:
file.write(str(soup))
song_names_spans = soup.select("li ul li h3")
print(song_names_spans)
using a list comprehension
songs_names_list = [song.getText().strip() for song in song_names_spans]
print(songs_names_list)
load_dotenv('.env')
CLIENT_ID = os.getenv("SPOTIPY_CLIENT_ID")
CLIENT_SECRET = os.getenv("SPOTIPY_CLIENT_SECRET")
REDIRECT_URI = os.getenv("SPOTIPY_REDIRECT_URI")
OAUTH_AUTHORIZE_URL = 'https://accounts.spotify.com/authorize'
OAUTH_TOKEN_URL = 'https://accounts.spotify.com/api/token'
scope = "playlist-modify-private", "Playlist-modify_public"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope="playlist-modify-private",
show_dialog=True,
cache_path="token.txt",
))
track_uris = []
for song_name in songs_names_list:
results = sp.search(q=song_name, type="track", limit=1)
tracks = results.get('tracks', {}).get('items', [])
# print(results)
try:
track_uri = tracks[0]["uri"]
track_uris.append(track_uri)
except IndexError:
print(f"{song_name} doesn't exist in Spotify. Skipped.")
pprint.pp(track_uris)
Create a private playlist
User_id = sp.current_user()["id"]
playlist_name = "My Python Playlist(Songs Names Only)"
playlist = sp.user_playlist_create(user=User_id, name=playlist_name, public=False)
pprint.pp(playlist)
add tracks to the playlist
if track_uris:
sp.playlist_add_items(playlist_id=playlist['id'], items=track_uris)
print(f"Playlist'{playlist_name}'has been created successfully!")
else:
print("No valid tracks found. Playlist not created")

billboard site is not responding. pls help
I had to add very specified search criteria when fetching information from Billboard site:
song_names_spans = soup.select("ul li ul li h3", id_="title-of-a-story", class_="c-title")
v-- I also had issue creating the playlist to Spotify. Code below resolved my issue, thank you @grizzleswens ! --v
grizzleswens commented on Mar 5, 2024
Here is my code, it is working perfectly, I had to have a little bit of hand holding from chat gptimport requests from bs4 import BeautifulSoup import spotipy from spotipy.oauth2 import SpotifyOAuth
Set your Spotify app credentials
You will need to make a spotify web app to get this data, go to spotify dev tools
SPOTIPY_CLIENT_ID = 'YOUR CLIENT ID' SPOTIPY_CLIENT_SECRET = 'YOUR CLIENT SECRET' SPOTIPY_REDIRECT_URI = 'YOUR REDIRECT URI' SCOPE = 'playlist-modify-public user-read-private'
date = input("What date would you like to travel back in time to? YYYY-MM-DD") endpoint = f"https://www.billboard.com/charts/hot-100/{date}/"
Scrape web for top 100 songs
response = requests.get(endpoint) html_data = response.text
soup = BeautifulSoup(html_data, "html.parser")
songs = soup.select("li ul li h3") songs_titles = [song.getText().strip() for song in songs]
track_uris = []
Authenticate with Spotify
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri=SPOTIPY_REDIRECT_URI, scope=SCOPE))
Find track URIs
for song in songs_titles: try: results = sp.search(q=f"track:{song}", type="track") track_uri = results['tracks']['items'][0]['uri'] track_uris.append(track_uri) except IndexError: continue
# Authenticate with Spotify
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri=SPOTIPY_REDIRECT_URI, scope=SCOPE))
Get current user's profile data
user_id = sp.current_user()['id']
Create a new playlist for the current user
playlist_name = f"Billboard top songs on {date}" playlist_description = "Created with Python" playlist = sp.user_playlist_create(user=user_id, name=playlist_name, description=playlist_description)
Get the playlist ID
playlist_id = playlist['id']
Add tracks to the playlist
sp.playlist_add_items(playlist_id=playlist_id, items=track_uris)
print(f"Playlist created and tracks added. Playlist ID: {playlist_id}")
To add the tracks to the playlist I used another spotipy method, I can't find the one in the solution in the documentation. According to PyCharm that method also doesn't exist. Here is my code I used:
``
import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os
from dotenv import load_dotenv
load_dotenv()
BILLBOARD_ENDPOINT= "https://www.billboard.com/charts/hot-100/"
BILLBOARD_HEADER = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0"}
# entered a fixed date for testing purposes
# date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD:")
date = "2022-12-12"
response = requests.get(url=f"{BILLBOARD_ENDPOINT}{date}",headers=BILLBOARD_HEADER)
soup = BeautifulSoup(response.text, "html.parser")
songs = soup.find_all(name="h3", class_="c-title a-no-trucate a-font-primary-bold-s u-letter-spacing-0021 lrv-u-font-size-18@tablet lrv-u-font-size-16 u-line-height-125 u-line-height-normal@mobile-max a-truncate-ellipsis u-max-width-330 u-max-width-230@tablet-only")
top_100_songs = []
for song in songs:
title = song.getText().strip()
top_100_songs.append(title)
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
scope="playlist-modify-private",
redirect_uri="http://example.com",
client_id=os.environ["SPOTIPY_CLIENT_ID"],
client_secret=os.environ["SPOTIPY_CLIENT_SECRET"],
show_dialog=True,
cache_path="token.txt",
username="***********"
)
)
user_id = sp.current_user()["id"]
track_uri_list = []
for song in top_100_songs:
search = sp.search(q=song,type="track")
try:
track_uri_list.append(search["tracks"]["items"][0]["uri"])
except IndexError:
print("Track not found")
playlist_name = f"{date} Billboard 100"
playlist = sp.user_playlist_create(user_id, playlist_name, public=False, description=f"Billboard top 10 from {date}")
playlist_id = playlist["id"]
print(f"playlist created with id {playlist_id}")
sp.user_playlist_add_tracks(user=user_id, playlist_id=playlist_id, tracks=track_uri_list)
print("tracks added")
``
After Executing the above code , i am getting below error
urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091)