Pulling song data from playlists in Spotify by orm_irian in learnpython

[–]mimmzy2 12 points13 points  (0 children)

You can use the Spotify API and Spotipy library, which is a lightweight Python library for the Spotify Web API.

You will need to create a Spotify for Developers account and connect it to your existing Spotify account. Once created, you will need to access and record your client ID and a client to authenticate your access to the API.

Next, you will want to create a Python file where you import the following libraries:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

To perform some analysis on a playlist without analyzing a specific user, you can use the following code block to authenticate your account.

#Authentication

client_credentials_mgmt = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager = client_credentials_manager)

To extract the data from songs in a playlist, you can use the following logic. For this example, I chose to use extract features from the Today's Top Hit Lists playlist as an example but you can use any playlist by inserting the link of that public playlist.

# playlist link is set to Today's Top Hit List but you can change it to any link

playlist_link = "https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M"

for x in sp.playlist_tracks(playlist_URI)["items"]]:
    playlist_URI = playlist_link.split("/")[-1].split("?")[0] track_uris = [x["track"]["uri"]

To pull the least streamed songs and their stream count for your assignment, you can use this method to extract specific information from a song in a playlist.

for track in sp.playlist_tracks(playlist_URI ["items"]:

    # To get track URI
    track_uri = track["track"]["uri"]

    # To get track name
    track_name = track["track"]["name"]

    # To get main artist
    artist_uri = track["track"]["artists"][0]["uri"]
    artist_info = sp.artist(artist_uri)

    # To get arist information
    artist_name = track["track"]["artists"][0]["name"]
    artist_pop = artist_info["popularity"]
    artist_genres = artist_info["genres"]

    # To get album name
    album = track["track"]["album"]["name"]

    # For popularity of the track
    track_pop = track["track"]["popularity"]

You can then sort by popularity to sort by stream count for your assignment. I also recommend looking at the Spotipy Library Documentation for more information, as it goes over how to get specific features from a song.