import requests import re #获取hush值和AlbumID def gethush(): global musicname musicname = input('请输入您要下载的歌曲名字:') url = 'http://songsearch.kugou.com/song_search_v2?callback=jQuery1910026785707623246724_1490845878865&keyword={}&page=1&pagesize=30&userid=-1&%20%20clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1490845878887'.format(musicname) response = requests.get(url) html = response.text pattern = '"FileHash":"(.*?)","SQPayType".*?"AlbumID":"(.*?)"' hush = re.search(pattern,html).group(1) album = re.search(pattern,html).group(2) return hush #获取音乐下载链接 def getmusicurl(hush): url = 'http://www.kugou.com/yy/index.php?r=play/getdata&hash={}'.format(hush) response = requests.get(url) html = response.text pattern = '"play_url":"(.*?)","authors"' music_url = re.search(pattern,html).group(1) return music_url #下载音乐 def downloadmusic(url): session = requests.Session() url = url.replace('\\','') r = requests.get(url) with open(r'd:\mp3\%s.mp3' % musicname, "wb") as f: for chunk in r.iter_content(chunk_size=512): if chunk: print('正在下载:%s'% musicname) f.write(chunk) def main(): downloadmusic(getmusicurl(gethush())) if __name__ == '__main__': main()