-
Notifications
You must be signed in to change notification settings - Fork 42
/
api.py
executable file
·271 lines (236 loc) · 9.35 KB
/
api.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/env python
#encoding: UTF-8
'''
网易云音乐 Api
'''
import re
import json
import requests
import hashlib
# list去重
def uniq(arr):
arr2 = list(set(arr))
arr2.sort(key=arr.index)
return arr2
default_timeout = 10
class NetEase:
def __init__(self):
self.header = {
'Accept': '*/*',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'music.163.com',
'Referer': 'http://music.163.com/search/',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36'
}
self.cookies = {
'appver': '1.5.2'
}
def httpRequest(self, method, action, query=None, urlencoded=None, callback=None, timeout=None):
if(method == 'GET'):
url = action if (query == None) else (action + '?' + query)
connection = requests.get(url, headers=self.header, timeout=default_timeout)
elif(method == 'POST'):
connection = requests.post(
action,
data=query,
headers=self.header,
timeout=default_timeout
)
connection.encoding = "UTF-8"
connection = json.loads(connection.text)
return connection
# 登录
def login(self, username, password):
action = 'http://music.163.com/api/login/'
data = {
'username': username,
'password': hashlib.md5( password ).hexdigest(),
'rememberLogin': 'true'
}
try:
return self.httpRequest('POST', action, data)
except:
return {'code': 501}
# 用户歌单
def user_playlist(self, uid, offset=0, limit=100):
action = 'http://music.163.com/api/user/playlist/?offset=' + str(offset) + '&limit=' + str(limit) + '&uid=' + str(uid)
try:
data = self.httpRequest('GET', action)
return data['playlist']
except:
return []
# 搜索单曲(1),歌手(100),专辑(10),歌单(1000),用户(1002) *(type)*
def search(self, s, stype=1, offset=0, total='true', limit=60):
action = 'http://music.163.com/api/search/get/web'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
return self.httpRequest('POST', action, data)
# 新碟上架 http://music.163.com/#/discover/album/
def new_albums(self, offset=0, limit=50):
action = 'http://music.163.com/api/album/new?area=ALL&offset=' + str(offset) + '&total=true&limit=' + str(limit)
try:
data = self.httpRequest('GET', action)
return data['albums']
except:
return []
# 歌单(网友精选碟) hot||new http://music.163.com/#/discover/playlist/
def top_playlists(self, category='全部', order='hot', offset=0, limit=50):
action = 'http://music.163.com/api/playlist/list?cat=' + category + '&order=' + order + '&offset=' + str(offset) + '&total=' + ('true' if offset else 'false') + '&limit=' + str(limit)
try:
data = self.httpRequest('GET', action)
return data['playlists']
except:
return []
# 歌单详情
def playlist_detail(self, playlist_id):
action = 'http://music.163.com/api/playlist/detail?id=' + str(playlist_id)
try:
data = self.httpRequest('GET', action)
return data['result']['tracks']
except:
return []
# 热门歌手 http://music.163.com/#/discover/artist/
def top_artists(self, offset=0, limit=100):
action = 'http://music.163.com/api/artist/top?offset=' + str(offset) + '&total=false&limit=' + str(limit)
try:
data = self.httpRequest('GET', action)
return data['artists']
except:
return []
# 热门单曲 http://music.163.com/#/discover/toplist 50
def top_songlist(self, offset=0, limit=100):
action = 'http://music.163.com/discover/toplist'
try:
connection = requests.get(action, headers=self.header, timeout=default_timeout)
connection.encoding = 'UTF-8'
songids = re.findall(r'/song\?id=(\d+)', connection.text)
if songids == []:
return []
# 去重
songids = uniq(songids)
return self.songs_detail(songids)
except:
return []
# 歌手单曲
def artists(self, artist_id):
action = 'http://music.163.com/api/artist/' + str(artist_id)
try:
data = self.httpRequest('GET', action)
return data['hotSongs']
except:
return []
# album id --> song id set
def album(self, album_id):
action = 'http://music.163.com/api/album/' + str(album_id)
try:
data = self.httpRequest('GET', action)
return data['album']['songs']
except:
return []
# song ids --> song urls ( details )
def songs_detail(self, ids, offset=0):
tmpids = ids[offset:]
tmpids = tmpids[0:100]
tmpids = map(str, tmpids)
action = 'http://music.163.com/api/song/detail?ids=[' + (',').join(tmpids) + ']'
try:
data = self.httpRequest('GET', action)
return data['songs']
except:
return []
# song id --> song url ( details )
def song_detail(self, music_id):
action = "http://music.163.com/api/song/detail/?id=" + str(music_id) + "&ids=[" + str(music_id) + "]"
try:
data = self.httpRequest('GET', action)
return data['songs']
except:
return []
# 今日最热(0), 本周最热(10),历史最热(20),最新节目(30)
def djchannels(self, stype=0, offset=0, limit=50):
action = 'http://music.163.com/discover/djchannel?type=' + str(stype) + '&offset=' + str(offset) + '&limit=' + str(limit)
try:
connection = requests.get(action, headers=self.header, timeout=default_timeout)
connection.encoding = 'UTF-8'
channelids = re.findall(r'/dj\?id=(\d+)', connection.text)
channelids = uniq(channelids)
return self.channel_detail(channelids)
except:
return []
# DJchannel ( id, channel_name ) ids --> song urls ( details )
# 将 channels 整理为 songs 类型
def channel_detail(self, channelids, offset=0):
channels = []
for i in range(0, len(channelids)):
action = 'http://music.163.com/api/dj/program/detail?id=' + str(channelids[i])
try:
data = self.httpRequest('GET', action)
channel = self.dig_info( data['program']['mainSong'], 'channels' )
channels.append(channel)
except:
continue
return channels
def dig_info(self, data ,dig_type):
temp = []
if dig_type == 'songs':
for i in range(0, len(data) ):
song_info = {
'song_id': data[i]['id'],
'artist': [],
'song_name': data[i]['name'],
'album_name': data[i]['album']['name'],
'mp3_url': data[i]['mp3Url']
}
if 'artist' in data[i]:
song_info['artist'] = data[i]['artist']
elif 'artists' in data[i]:
for j in range(0, len(data[i]['artists']) ):
song_info['artist'].append( data[i]['artists'][j]['name'] )
song_info['artist'] = ', '.join( song_info['artist'] )
else:
song_info['artist'] = '未知艺术家'
temp.append(song_info)
elif dig_type == 'artists':
temp = []
for i in range(0, len(data) ):
artists_info = {
'artist_id': data[i]['id'],
'artists_name': data[i]['name'],
'alias': ''.join(data[i]['alias'])
}
temp.append(artists_info)
return temp
elif dig_type == 'albums':
for i in range(0, len(data) ):
albums_info = {
'album_id': data[i]['id'],
'albums_name': data[i]['name'],
'artists_name': data[i]['artist']['name']
}
temp.append(albums_info)
elif dig_type == 'playlists':
for i in range(0, len(data) ):
playlists_info = {
'playlist_id': data[i]['id'],
'playlists_name': data[i]['name'],
'creator_name': data[i]['creator']['nickname']
}
temp.append(playlists_info)
elif dig_type == 'channels':
channel_info = {
'song_id': data['id'],
'song_name': data['name'],
'artist': data['artists'][0]['name'],
'album_name': 'DJ节目',
'mp3_url': data['mp3Url']
}
temp = channel_info
return temp