for the following code I am getting
Traceback (most recent call last): File "main.py", line 24, in artist_uri = json_data['artists']['items'][0]['id'] IndexError: list index out of range.
Anyone can tell me how to solve this?
for item in (fd):
artist = item['Name']
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer xxxxx',
}
params = (
('q', artist),
('type', 'artist'),
)
response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
json_data = json.loads(response.text) # convert json response to text/dict
artist_uri = json_data['artists']['items'][0]['id']
print(artist_uri)
This is because the artist: "ANAVITÃÂRIA" cannot be retrieved from the Spotify API. The following is the response your script get when you try it:
{
"artists" : {
"href" : "https://api.spotify.com/v1/search?query=ANAVIT%C3%83%C2%83%C3%82%C2%93RIA&type=artist&offset=0&limit=20",
"items" : [ ],
"limit" : 20,
"next" : null,
"offset" : 0,
"previous" : null,
"total" : 0
}
Sometimes it is might be due to the characters in the name. To avoid this error, rate-limiting issue and continue the loop you can check whether there are data in the current API response and also the status code of the API Response Check the updated code: (Please update the bearer token when you try it)
import pandas as pd
import requests
import json
import time
fd = pd.read_csv('fd.csv',sep=';',encoding='latin1') # Reading data from csv
fd = fd.T.to_dict().values() # Converting dataframe into list of dictionaries
for item in (fd):
artist = item['Name']
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer xxxxxx',
}
params = (
('q', artist),
('type', 'artist'),
)
response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
if response.status_code != 429:
json_data = json.loads(response.text) # convert json response to text/dict
if (len(json_data['artists']['items']) > 0):
artist_uri = json_data['artists']['items'][0]['id']
print(artist_uri)
else:
time.sleep(30)
response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
json_data = json.loads(response.text) # convert json response to text/dict
if (len(json_data['artists']['items']) > 0):
artist_uri = json_data['artists']['items'][0]['id']
print(artist_uri)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.