在名称之间存在空格的某些情况下,为每个返回的相册获取曲目不起作用

时间:2017-11-22 18:19:13

标签: python

我正在接收来自特定国家的顶级艺术家,该艺术家的专辑以及来自lastfm api的专辑的曲目。我没有错误地收到艺术家和专辑,但是在曲目中它出现了:

for album in album_response['album']['tracks']['track']: KeyError: 'album'

问题似乎是因为一些艺术家的名字中有空格,所以我用“+”替换它也用“%2b”替换它,但没有解决方案正常工作它总是出现上面的错误。

chosen = artists[i]['name'].replace(" ", "+")
chosen = '+'.join(artists[i]['name'].lower().split())
chosen = artists[i]['name'].replace(" ", "%2B")

轨道部分出错:

tracks = {}
for i,v in albums.items():
    artist = albums[i]['artist'].replace(" ","+")
    name = albums[i]['name'].replace(" ", "+")
    album_response_data = requests.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&format=json&api_key='+api_key+'&artist='+artist+'&album='+name)
    album_response = album_response_data.json()

    print(album_response)      
    for album in album_response['album']['tracks']['track']:


        title = album['name']
        number = album['@attr']['rank']
        duration = album['duration']

        tracks[ID] = {}
        tracks[ID]['title'] = title
        tracks[ID]['number'] = number
        tracks[ID]['artist'] = albums[i]['artist']
        tracks[ID]['album'] = albums[i]['name']
        tracks[ID]['albumID'] = albums[i]['ID']
        tracks[ID]['duration'] = duration

        ID += 1

完整的工作示例:

import requests

api_key = "b088cbedecd40b35dd89e90f55227ac2" #generated for the example
ID= 0

#Get artists from specific country

artists = {}
for i in range(2, 3):
    artists_response = requests.get(
        'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page=' + str(i) + '&api_key=' + api_key)
    artists_data = artists_response.json()
    for artist in artists_data["topartists"]["artist"]:

        name = artist["name"]

        url = artist["url"]
        #if ID > 3 continue
        artists[ID] = {}
        artists[ID]['ID'] = ID
        artists[ID]['name'] = name

        ID += 1


#Get TopAlbums info from above artists

albums = {}
for i, v in artists.items():
    chosen = artists[i]['name'].replace(" ", "+")
    topalbums_response = requests.get(
        'http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&format=json&artist=' + chosen + '&api_key=' + api_key + '&limit=5')
    albums_data = topalbums_response.json()

    for album in albums_data['topalbums']['album']:
        name = album["name"]
        url = album["url"]

        albums[ID] = {}
        albums[ID]['ID'] = ID
        albums[ID]['artist'] = artists[i]['name']
        albums[ID]['artistID'] = artists[i]['ID']
        albums[ID]['name'] = name
        albums[ID]['url'] = url

        ID += 1

#Get tracks info of the above albums

tracks = {}
for i,v in albums.items():
    artist = albums[i]['artist'].replace(" ","+")
    name = albums[i]['name'].replace(" ", "+")
    album_response_data = requests.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&format=json&api_key='+api_key+'&artist='+artist+'&album='+name)
    album_response = album_response_data.json()


    for album in album_response['album']['tracks']['track']:  

            title = album['name']

            number = album['@attr']['rank']
            duration = album['duration']

            tracks[ID] = {}

            tracks[ID]['trackID'] = ID

            tracks[ID]['title'] = title
            tracks[ID]['number'] = number
            tracks[ID]['artist'] = albums[i]['artist']
            tracks[ID]['album'] = albums[i]['name']
            tracks[ID]['albumID'] = albums[i]['ID']
            tracks[ID]['duration'] = duration

            ID += 1

1 个答案:

答案 0 :(得分:1)

问题不在于某些艺术家在名称中有空格,而是因为您的album_response字典并不总是有一个名为album的键。

在for循环中添加print album_response.keys(),如下所示,

artist = albums[i]['artist'].replace(" ","+")
name = albums[i]['name'].replace(" ", "+")
album_response_data = requests.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&format=json&api_key='+api_key+'&artist='+artist+'&album='+name)
album_response = album_response_data.json()

print album_response.keys() # ADDED HERE

for album in album_response['album']['tracks']['track']:  
    title = album['name']

我得到以下输出:

>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'album']
>>> [u'message', u'links', u'error']
>>> Traceback (most recent call last):
    File "test.py", line 58, in <module>
    for album in album_response['album']['tracks']['track']:
    KeyError: 'album'

请注意,在错误发生之前,album_response.keys()没有“相册”作为关键字。我不确定你想怎么处理这个,但如果你只是想忽略这种情况,只需添加一个这样的if语句:

tracks = {}
for i,v in albums.items():
    artist = albums[i]['artist'].replace(" ","+")
    name = albums[i]['name'].replace(" ", "+")
    album_response_data = requests.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&format=json&api_key='+api_key+'&artist='+artist+'&album='+name)
    album_response = album_response_data.json()

    if 'album' in album_response.keys():
        for album in album_response['album']['tracks']['track']:  

                title = album['name']

                number = album['@attr']['rank']
                duration = album['duration']

                tracks[ID] = {}

                tracks[ID]['trackID'] = ID

                tracks[ID]['title'] = title
                tracks[ID]['number'] = number
                tracks[ID]['artist'] = albums[i]['artist']
                tracks[ID]['album'] = albums[i]['name']
                tracks[ID]['albumID'] = albums[i]['ID']
                tracks[ID]['duration'] = duration

                ID += 1