运行后直接输入想找的歌名,选择搜索结果下载文件到本地桌面。
运行前需要安装相关库。
只支持下载128kbps的MP3文件
如果出现无法下载,可以尝试更新new_headers
供爬虫爱好者学习使用
"""
Version: Python3.7
Author: ZM
Time: 2020/3/22
"""
import re
import json
import time
import requests
from fake_useragent import UserAgent
ua = UserAgent()
def get_song(song_name):
global download_url
search_url = "https://songsearch.kugou.com/song_search_v2?callback=jQuery112408397851079788055_1557731496992&page" \
"=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_fil" \
"ter=0&_=1557731496997&keyword={}".format(song_name)
headers = {
"Referer": "https://www.kugou.com/yy/html/search.html",
"UserAgent":ua.random
}
res = requests.get(search_url, headers=headers)
start = re.search("jQuery\d+_\d+\(?", res.text)
js = json.loads(res.text.strip().lstrip(start.group()).rstrip(")")) # 注意:末尾有一个换行需要去掉
song_list = js['data']['lists']
for i in range(15):
print(str(i + 1) + ">>>" + str(song_list[i]['FileName']).replace('<em>', '').replace('</em>', ''))
num = int(input("\n请输入您想要下载的歌曲序号:"))
print("请稍等,下载歌曲中...")
time.sleep(1)
file_hash = song_list[num-1]['FileHash']
download_songname = str(song_list[num-1]['FileName']).replace('<em>', '').replace('</em>', '')
print(download_songname)
new_headers = {"User-Agent":ua.random,"accept":"*/*","accept-encoding": "gzip, deflate, br","accept-language": "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7","cookie": "kg_mid=09ef63699c5de255b926c7fc51d9f288; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1583933945,1585059353; kg_dfid=3LF0gs3wKisZ0c8Oqj1hdALj; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1585060087; kg_mid_temp=09ef63699c5de255b926c7fc51d9f288",'origin': 'http://www.kugou.com/', 'referer': 'http://www.kugou.com/'}
hash_url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery191015071006070477466_1585061464206&hash='+file_hash
hash_content = requests.get(hash_url,headers=new_headers).text
play_url =re.findall('"play_url":"(.*?)"',hash_content)
if play_url ==['']:
print('歌曲无法下载')
next = input('是否继续下载其他歌曲(y/n):>>')
if next.lower() =='y':
next_songname = input("请输入您想要搜索的歌曲:")
get_song(next_songname)
else:
print('输入错误')
else:
play_url =''.join(play_url)
download_url =play_url.replace('\\','')
try:
with open(download_songname+'.mp3','wb')as fp:
fp.write(requests.get(download_url).content)
print('歌曲《{}》下载成功'.format(download_songname))
except Exception as e:
print(e)
while True:
if __name__ == '__main__':
get_song(input("请输入您想要搜索的歌曲:"))
choice = input('是否继续下载其他歌曲(y/n):>>')
if choice.lower() =='y':
continue
else:
break