如何从Spotify API嵌套字典提取专辑信息并生成DataFrame
从Spotify搜索结果中提取专辑信息并生成DataFrame
解决方案步骤
返回的搜索结果是嵌套字典结构,专辑数据存放在album_uri_research['albums']['items']列表中,每个列表元素对应一张专辑的完整信息。我们需要从中提取专辑的name和uri字段,再用Pandas生成指定列的DataFrame。
完整代码实现
import spotipy from spotipy.oauth2 import SpotifyClientCredentials import json import pandas as pd # 认证部分(保留原有代码) credentials = json.load(open('autorizzazione.json')) client_id = credentials['client_id'] client_secret = credentials['client_secret'] client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) # 搜索专辑 album_uri_research = sp.search("The Iron Giant", limit=1, offset=0, type='album', market=None) # 提取专辑数据 album_items = album_uri_research['albums']['items'] album_data = [] for album in album_items: # 提取专辑的name和uri(直接取专辑字典下的字段,与艺术家uri区分开) album_info = { "专辑名称": album['name'], "专辑uri": album['uri'] } album_data.append(album_info) # 生成DataFrame df = pd.DataFrame(album_data) print(df)
代码说明
album_uri_research['albums']['items']:定位到搜索返回的专辑列表,用循环处理适配后续调整limit值提取多张专辑的场景。- 直接访问专辑字典下的
name和uri:这两个字段属于专辑本身,和艺术家列表中的uri(艺术家专属)完全独立,不会混淆。
输出示例
专辑名称 专辑uri 0 The Iron Giant (Original Score) spotify:album:5ZeshDZM1ESVRgD1QLzDGg
内容的提问来源于stack exchange,提问作者TF7
相关产品推荐
相关产品推荐

