2

Using Spotipy I'm trying to list the tracks by supplied the name of the artist and album.

This should be quite straight forward, however I don't know how to get the albumID in order to get the tracklist. I thought it would be something like:

sp.album_tracks(q = "album:" + album, type = "album")

...only that doesn't work.

Here's what I've got so far. It will successfully get the albums for selected artist (hard coded here as "Phosgore" for no particular reason other than they only have three albums and I didn't want to get swamped with dictionary):

#!/usr/bin/python
# -*- coding: utf-8 -*-

# shows album from trackname

import sys
import spotipy

def get_albums_from_artist_name(name):

  results = sp.search(q = "artist:" + name, type = "artist")
  items = results["artists"]["items"]
  if len(items) == 0:
    return None
  else:
    d = items[0]

  # get artistID and artist name from dict
  artID = d["id"]     # 3Cf1GbbU9uHlS3veYiAK2x
  aName = d["name"]   # Phosgore

  artistUri = "spotify:artist:" + artID

  results = sp.artist_albums(artistUri, album_type = "album")
  albums = results["items"]
  while results["next"]:
    results = sp.next(results)
    albums.extend(results["items"])

  unique = set() # ignore duplicate albums
  for album in albums:
    name = album["name"]
    if not name in unique: 
      unique.add(name) # unique is a set

  print ("\nAlbums by %s:\n" %(aName))
  unique = list(unique)
  for i in range(0, len(unique)):
    print unique[i]

  # let's return a list instead of a set
  return list(unique)

#------------------------------------------------
def get_tracks_from_album(album):
  tracks = []
  # results = sp.album_tracks(q = "album:" + album, type = "album")
  # don't know how to get album id
  # list tracks here


sp = spotipy.Spotify()
sp.trace = False

ask = "Phosgore"

artistAlbums = get_albums_from_artist_name(ask)

get_tracks_from_album("Pestbringer")
4

1 回答 1

4

获取uri专辑的 并将其传递给.album_tracks()方法:

import spotipy

sp = spotipy.Spotify()
sp.trace = False

# find album by name
album = "Pestbringer"
results = sp.search(q = "album:" + album, type = "album")

# get the first album uri
album_id = results['albums']['items'][0]['uri']

# get album tracks
tracks = sp.album_tracks(album_id)
for track in tracks['items']:
    print(track['name'])

印刷:

Embrace Our Gift
Here Comes the Pain
Pestbringer
Dein Licht
Aggression Incarnate
Countdown to Destruction
Nightmare
Noise Monsters
Lobotomy
The Holy Inquisition
Tote Musikanten
于 2016-05-01T12:09:02.040 回答