-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify_api_scraper - SE.py
133 lines (105 loc) · 4.34 KB
/
spotify_api_scraper - SE.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import requests
import base64
import pandas as pd
URL_SPOTYFY = 'https://api.spotify.com/v1'
EP_ARTIST = '/artists/{artist_id}'
URL_SPOTYFY_SRCH = 'https://api.spotify.com/v1/search'
TOKEN = 'https://accounts.spotify.com/api/token'
def encoding():
''' Function that encodes the client id and client secret into base64'''
client_id = "CLIENT ID HERE : CLIENT SECRET HERE"
msg_bytes = client_id.encode("UTF-8")
msg_base64 = base64.b64encode(msg_bytes)
msg_decode = msg_base64.decode("UTF-8")
return msg_decode
def get_token():
''' Function that updates the token '''
params = {'grant_type': 'client_credentials'}
headers = {'Authorization': 'Basic ' + encoding()}
r_spoty = requests.post(TOKEN, headers=headers, data=params)
if r_spoty.status_code != 200:
print('Error en la requests', r_spoty.json())
return r_spoty.json()["access_token"]
def get_artist_id(artist):
''' Function that finds the ID for a search artist '''
token = get_token()
header = {'Authorization': 'Bearer {}'.format(token)}
srch_params = {'q' : artist, 'type' : 'artist'}
get_url = requests.get(URL_SPOTYFY_SRCH, headers=header, params=srch_params)
df = pd.DataFrame(get_url.json()['artists']['items'])
artist_id = df.sort_values(by = "popularity", ascending= False).iloc[0]['id']
return artist_id
def obtener_discografia(artist_id, return_name = False, page_limit = 50, country = None):
''' Function that obtains the albums of the desire artist '''
token = get_token()
url = f'https://api.spotify.com/v1/artists/{artist_id}/albums'
header = {'Authorization': 'Bearer {}'.format(token)}
params = {'limit': page_limit,
'offset': 0,
'country': country}
lista = []
r = requests.get(url, headers = header, params = params)
if r.status_code != 200:
print('Error en la requets')
return None
if return_name:
lista += [(item['id'], item['name'],"Año:{}".format(item['release_date']) ) for item in r.json()['items']]
else:
lista += [(item['name'],"Año:{}".format(item['release_date'])) for item in r.json()['items']]
'''
while r.json()['next']:
r = requests.get(r.json()['next'], headers = header)
if return_name:
lista += [(item['id'], item['name']) for item in r.json()['items']]
else:
lista += [item['id'] for item in r.json()['items']]
'''
return lista
def get_tracks(discografia_id, return_name = False, page_limit = 50, market = None):
''' Function that gets all the tracks inside a specific album '''
album_id = str(input('Please input the album\'s id: '))
token = get_token()
url = f'https://api.spotify.com/v1/albums/{album_id}/tracks'
header = {'Authorization': 'Bearer {}'.format(token)}
params = {
'limit': page_limit,
'offset': 0
}
tracks = []
r = requests.get(url, headers = header, params = params)
if r.status_code != 200:
print('Error en la requests')
return None
if return_name:
tracks += [(i['id'], i['name']) for i in r.json()['items']]
else:
tracks += [(i['name']) for i in r.json()['items']]
return tracks
def run():
print('This program will obtain the Discography of a giving artist')
artist_name = str(input('Please give me a artist name: '))
artist_id = get_artist_id(artist_name)
discografia = obtener_discografia(artist_id, return_name = True)
discografia_id = obtener_discografia(artist_id, return_name = True)
print('This is the Discography:')
counter = 1
for i in discografia:
print(counter, i)
counter += 1
while True:
choice = str(input("Do you wish to know the songs from any album? y/n: "))
if choice == "y":
tracks = get_tracks(discografia_id)
print('This are the songs of the chosen album:')
counter = 1
for i in tracks:
print(counter, i)
counter += 1
break
elif choice == "n":
print('Closing the program')
break
else:
print('Please input a valid answer')
if __name__ == '__main__':
run()