2

I've been trying to create a simple tool that converts apple music playlists to Spotify playlists using web scraping and Spotipy.

I broke each part of this tool into various functions. My function to scrape the apple website and create a playlist works fine but adding the tracks doesn't. It just shows an empty playlist on my Spotify account

This is the function that is supposed to search and add the tracks.

I commented out previous search/query methods.

def get_spotify_tracks(songs, artists, sp, user_id):
'''
Step 4: Transfer fetched song data
Step 5: Search for song on Spotify
Step 6: Add the songs to the Spotify playlist
'''
list_of_tracks = []
prePlaylist = sp.user_playlists(user=user_id)
playlist = prePlaylist["items"][0]["id"]
for playlist_song, song_artist in zip(songs, artists):
    track_id = sp.search(q='artist:' + song_artist + ' track:' + playlist_song, type='track')

    #track_data = list(f'{playlist_song} by {song_artist}')
    #result = sp.search(q=track_data, )
    #query = f"https://api.spotify.com/v1/serch?query=track%3A{playlist_song}" \
    #        f"+artist%3A{song_artist}&type=track&offset=0&limit=5"

    list_of_tracks.append(track_id["tracks"]["items"][0]["uri"])
    print(list_of_tracks)
query = f"https://api.spotify.com/v1/playlists/{playlist}/tracks"
response = requests.post(
    query,
    data=list_of_tracks,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
)
return list_of_tracks

This is the complete code. Executing main() creates a playlist with the right name and description but no tracks.

'''
Making a program that converts an Apple music playlist to a Spotify Playlist

Step1: Fetch the Apple music playlist data
Step2: Get Authorization to spotify account
Step3: Create new spotify playlist
Step4: Transfer fetched song data
Step5: Search for song on Spotify
Step6: Add the songs to Spotify playlist
'''

clientid = os.environ['CLIENT_ID']
client_secret = os.environ['CLIENT_SECRET']
token = os.environ['ACCESS_TOKEN']
username = os.environ['USERNAME']
track_list = []
artist_list = []


def get_apple_playlist(URL):
    '''
    Step1: Fetch the Apple music playlist data
    '''
    headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
    "Accept-Language": "en-US,en;q=0.9"
    }
    # pass in apple playlist link
    apple_link = requests.get(URL, headers=headers)
    # Use Beautiful soup to retrieve page html
    playlist_soup = BeautifulSoup(apple_link.content, "lxml")

    # Find various playlist info with Beautiful soup
    playlist_name = playlist_soup.find('h1', attrs={'data-testid': 'non-editable-product-title'}).get_text(strip=True)

    playlist_description = playlist_soup.find('p', attrs={'data-testid': 'truncate-text'}).get_text(strip=True)

    songs_raw = playlist_soup.find_all("div", class_="songs-list-row__song-name")

    artists_raw = playlist_soup.find_all("div", class_="songs-list__col songs-list__col--artist typography-body")
    #song_art = [playlist_soup.find_all("div picture source", type="image/jpeg").get_]

    #Refining data
    for song in songs_raw:
        track_list.append(song.get_text(strip=True))

    for artist in artists_raw:
        artist_list.append(artist.get_text(strip=True))

    return playlist_name, playlist_description, track_list, artist_list

def spotify_playlist(playlist_name, playlist_description):
    '''
    Step 2: Get Authorization to spotify account
    Step 3: Create new spotify playlist
    '''
    token = SpotifyOAuth(client_id=clientid,
                         client_secret=client_secret,
                         redirect_uri="http://127.0.0.1:8080/",
                         scope="playlist-modify-public")
    
    sp = spotipy.Spotify(auth_manager=token)
    user_id = sp.current_user()['id']

    new_playlist = sp.user_playlist_create(user=user_id, name=playlist_name, description=playlist_description, public=True)
    playlist_id = new_playlist['id']

    return playlist_id, user_id, sp


def get_spotify_tracks(songs, artists, sp, user_id):
    '''
    Step 4: Transfer fetched song data
    Step 5: Search for song on Spotify
    Step 6: Add the songs to the Spotify playlist
    '''
    list_of_tracks = []
    prePlaylist = sp.user_playlists(user=user_id)
    playlist = prePlaylist["items"][0]["id"]
    for playlist_song, song_artist in zip(songs, artists):
        track_id = sp.search(q='artist:' + song_artist + ' track:' + playlist_song, type='track')

        #track_data = list(f'{playlist_song} by {song_artist}')
        #result = sp.search(q=track_data, )
        #query = f"https://api.spotify.com/v1/serch?query=track%3A{playlist_song}" \
        #        f"+artist%3A{song_artist}&type=track&offset=0&limit=5"

        list_of_tracks.append(track_id["tracks"]["items"][0]["uri"])
        print(list_of_tracks)
    query = f"https://api.spotify.com/v1/playlists/{playlist}/tracks"
    response = requests.post(
        query,
        data=list_of_tracks,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }
    )
    return list_of_tracks


def main(url):
    '''
    Execution
    '''
    playlist_data = get_apple_playlist(url)
    playlist = spotify_playlist(playlist_data[0], playlist_data[1])
    tracks = get_spotify_tracks(playlist_data[2], playlist_data[3], playlist[2], playlist[1])

main("https://music.apple.com/ng/playlist/angry/pl.u-PDbYmE4Ie084DqR")
Robinson T
  • 101
  • 2

0 Answers0