Spotipy:尝试访问播放列表时,“TypeError:'NoneType' 对象不可下标”

Posted

技术标签:

【中文标题】Spotipy:尝试访问播放列表时,“TypeError:\'NoneType\' 对象不可下标”【英文标题】:Spotipy: ‘TypeError: 'NoneType' object is not subscriptable’ when trying to access playlistsSpotipy:尝试访问播放列表时,“TypeError:'NoneType' 对象不可下标” 【发布时间】:2021-11-14 02:16:57 【问题描述】:

重新访问一些用于通过 Spotify API 获取音乐功能数据的旧代码,现在当我尝试重新运行它时遇到此错误。

这是我的代码的要点:

https://github.com/rjdkirk/spotipy_study/blob/main/Spotify_playlists_v1.py

更具体地说,这是在 Spotify 身份验证之后的主要功能:

def analyze_playlist(creator, playlist_id):

    playlist_features_list = ["artist","album","track_name","track_id","acousticness","danceability","energy","key","loudness","mode","speechiness","instrumentalness","liveness","valence","tempo","duration_ms","time_signature"]

    playlist_df = pd.DataFrame(columns = playlist_features_list)

    playlist = sp.user_playlist_tracks(creator, playlist_id)["items"]
    for track in playlist:
        playlist_features = 
        playlist_features["artist"] = track["track"]["album"]["artists"][0]["name"]
        playlist_features["album"] = track["track"]["album"]["name"]
        playlist_features["track_name"] = track["track"]["name"]
        playlist_features["track_id"] = track["track"]["id"]

        audio_features = sp.audio_features(playlist_features["track_id"])[0]
        for feature in playlist_features_list[4:]:
            playlist_features[feature] = audio_features[feature]

        track_df = pd.DataFrame(playlist_features, index = [0])
        playlist_df = pd.concat([playlist_df, track_df], ignore_index = True)

    return playlist_df

输出有错误,只在一个播放列表上运行测试程序:

Traceback (most recent call last):
  File "Spots_test.py", line 34, in <module>
    playlists_df = analyze_playlist('Spotify', '37i9dQZF1DWZd79rJ6a7lp')
  File "Spots_test.py", line 27, in analyze_playlist
    playlist_features[feature] = audio_features[feature]
TypeError: 'NoneType' object is not subscriptable

据我所知,问题似乎是播放列表中的特定曲目,但我不知道如何解决它。我找到了这个,但我一直在尝试实施修复:

Python 'NoneType' TypeError when trying to access dictionary data

任何建议都非常感谢,谢谢!

【问题讨论】:

请在此处分享您的代码minimal reproducible example 我不确定,但我怀疑空的播放列表会返回 None 并且您正在尝试在考虑预期返回类型的情况下对其执行操作。如果您可以显示错误回溯,那将很有帮助... 【参考方案1】:

使用 try: except: 找到解决方案

try:
    for feature in playlist_features_list[4:]:
        playlist_features[feature] = audio_features[feature]
except:
    pass

我已经看到很多关于忽略 NoneTypes 是好还是坏的做法的讨论,所以我可能会回到它,但现在它有效。

【讨论】:

以上是关于Spotipy:尝试访问播放列表时,“TypeError:'NoneType' 对象不可下标”的主要内容,如果未能解决你的问题,请参考以下文章

Spotipy - 从公共播放列表访问曲目,无需身份验证

获得使用 Python3 的 spotipy 修改 Spotify 播放列表的授权

Spotipy 尝试使用 oauth 进行验证

使用 Spotipy 将曲目添加到播放列表时出现多个错误

将多个范围与 spotipy 一起使用

如何遍历 Spotipy 的 playlist_items 函数中的嵌套列表并仅打印出我感兴趣的字段?