从last.fm获取热门专辑

时间:2017-11-19 01:15:05

标签: python last.fm

我从lastfm api获得特定国家的顶级艺术家。我在artists{}中获得了每个艺术家和商店的名称,并取得了成功:

import requests

api_key = "0929f1144e531702a5563c887cbbade0"

ID = 0
artists = {}

for i in range(1, 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"]

        artists[ID] = {}
        artists[ID]['ID'] = ID
        artists[ID]['name'] = name
        ID += 1

但现在,对于每个艺术家,我想获得前5张专辑并存储在albums{},艺术家名称,艺术家ID,专辑名称和专辑的网址。

例如,对于每个艺术家,我想为前5张专辑的每张专辑获得一条记录,如下所示:

 "Artist": "U2", "ID": 175, "ArtistID": 10, "Title": Achtung    Baby",  
 "Image": "https://lastfm-img2.akamaized.net/i/u/174s/a482040d21924ddacd5fe75dedbb1ef2.png"},
 "URL": "https://www.last.fm/music/U2/Achtung+Baby"}, "487": {"Date": "2004-01-01"

 "Artist": "U2", "ID": 176, "ArtistID": 10, "Description": "None", "Title": "Boy", 


 ... and then the same for the other 3 albums of the top5

我使用下面的代码执行此操作,但它无法正常工作。 artistId始终显示为“0”,它只显示第一位艺术家的5张专辑。你知道问题出在哪里吗?

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

        for image in album['image']:
            if (image["size"] == "large"):
                if (image["size"] is not None):
                    image = image["#text"]
                    albums[ID]['image'] = image

        ID += 1

        print(albums)

1 个答案:

答案 0 :(得分:0)

尝试更改相册循环,如下所示:

for _, v in artists.items():
    chosen = v['name'].replace(" ", "+")

此外,我注意到你在艺术家的开头指定ID = 0,但在相册中引用它,你可能想看一下。

==== 编辑:

以下代码适用于我,虽然我不确定您希望获得哪种格式,因此它不完整。

import requests

api_key = "0929f1144e531702a5563c887cbbade0"

artists_url = (
    'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists'
    '&country=spain&format=json&page={}&api_key={}'
)

artists = []

for page in range(1, 3):
    artists_data = requests.get(artists_url.format(str(page), api_key)).json()
    for ID, artist in enumerate(artists_data["topartists"]["artist"]):
        artists.append((ID, artist["name"]))


albums = {}
albums_url = (
    'http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums'
    '&format=json&artist={}&api_key={}&limit=5'
)


for ID, artist in artists[:3]:   ### LIMITED to first three artists for testing.
    print('\n------\n{} {}'.format(ID, artist))
    chosen = artist.replace(" ", "+")
    albums_data = requests.get(albums_url.format(chosen, api_key)).json()

    for album in albums_data['topalbums']['album']:

        name = album["name"]
        url = album["url"]
        print('{}\n{}'.format(name, url))
        print(album)
        print()
#        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
#
#        for image in album['image']:
#            if (image["size"] == "large"):
#                if (image["size"] is not None):
#                    image = image["#text"]
#                    albums[ID]['image'] = image
#
#        ID += 1
#
#        print(albums)
#        print()