import requests
import json
class KuGou:
def __init__(self, search_kw):
'''
self.search_url --> 搜索URL
self.hash_url ---> 传入hash获得歌曲url与歌词
:param search_kw: 需要搜索的歌曲或歌手
'''
self.search_url = 'http://songsearch.kugou.com/song_search_v2?callback=jQuery11240180593475130568_1542792461367&keyword={}&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1542792461369'.format(
search_kw)
self.hash_url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19109053666197784564_1542792630445&hash={}&album_id={}&_=1542792630447'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
self.seesion = requests.Session()
self.seesion.headers = headers
def get_song_list(self):
'''
搜索到的歌曲列表
默认第一首歌曲,其他的更改下标[0]
:return:
'''
res = self.seesion.get(self.search_url)
res = res.text.strip('jQuery11240180593475130568_1542792461367(')[:-2]
# 只看第一首,修改下标[0],查看其它
song_name = json.loads(res)['data']['lists'][0]['SongName'].strip('<em>').strip('</em>')
song_hash = json.loads(res)['data']['lists'][0]['FileHash']
album_id = json.loads(res)['data']['lists'][0]['AlbumID']
# print(song_name,song_hash)
self.get_music(song_hash, song_name,album_id)
def get_music(self, song_hash, song_name,album_id):
'''
:param song_hash: 歌曲的hash
:param song_name: 歌曲的名字
:return:
'''
res = self.seesion.get(self.hash_url.format(song_hash,album_id))
res = json.loads(res.text.strip('jQuery19109053666197784564_1542792630445(')[:-2])
lrc = res['data']['lyrics'].replace('\r\n', '\n')
music_url = res['data']['play_url']
with open(song_name + '.lrc', 'w') as f:
f.write(lrc)
with open(song_name + '.mp3', 'wb') as f:
f.write(self.seesion.get(music_url).content)
def run(self):
'''
程序运行入口
:return:
'''
self.get_song_list()
if __name__ == '__main__':
k = KuGou('如约而至')
k.run()