从相册中获取 Spotipy 相册 ID

Get Spotipy album ID from album

我正在尝试使用 Spotipy 按提供的艺术家和专辑名称列出曲目。

这应该很简单,但是我不知道如何获取 albumID 才能获取曲目列表。我认为它会是这样的:

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

...只有那行不通。

这是我目前所知道的。它将成功获得选定艺术家的专辑(这里硬编码为 "Phosgore",没有特别的原因,除了他们只有三张专辑,我不想被字典淹没):

#!/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")

获取相册的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