【问题标题】:Get Spotipy album ID from album从专辑中获取 Spotipy 专辑 ID
【发布时间】:2016-03-26 16:06:18
【问题描述】:

使用 Spotipy,我试图通过提供艺术家和专辑的名称来列出曲目。

这应该很简单,但是我不知道如何获取专辑 ID 以获取曲目列表。我以为会是这样的:

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")

【问题讨论】:

    标签: python-2.7 spotify spotipy


    【解决方案1】:

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

    【讨论】:

    • # alecxe 这行得通!但在我奖励积分之前,请您告诉我专辑 ID 到底是什么以及它是如何工作的。 Python 说它是 unicode,但它看起来像一个包含 4 个项目的列表。谢谢
    • @GhoulFool 是的,我认为 spotify API 文档非常擅长解释 ID 和 URI 的格式,请参阅 developer.spotify.com/web-api/user-guide/#spotify-uris-and-ids。乐意效劳。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多