import requests
import json
import os
def music_download(name = "我的天空", count=1, download_Path="E://music_Dowload//"):
"""
:param name: 歌曲名称,默认为"我的天空"
:param count: 最大的歌曲版本个数,默认为1个
:param download_Path: 下载保存路径
:return:
"""
# name = input("请输入音乐名称:")
url = "https://www.kuwo.cn/api/www/search/searchMusicBykeyWord?"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400",
"Cookie": "_ga=GA1.2.1083049585.1590317697; _gid=GA1.2.2053211683.1598526974; _gat=1; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1597491567,1598094297,1598096480,1598526974; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1598526974; kw_token=HYZQI4KPK3P",
"Referer": "http://www.kuwo.cn/search/list?key=%E5%91%A8%E6%9D%B0%E4%BC%A6",
"csrf": "HYZQI4KPK3P",
}
params = {
"key": name, # 歌曲名称
"pn": "1",
"rn": count, # 返回搜索结果的最大数量
"httpsStatus": "1",
"reqId": "431ff5a0 - 54d4 - 11eb - 876b - e7e8d61ed87a"
}
response = requests.get(url=url, headers=headers, params=params).text # 获取搜索音乐列表数据
data = json.loads(response)
dataPack = data["data"]["list"] # 拿到
musicList = [] # 储存搜索出来的结果
for i in dataPack:
music_name = i["name"] # 歌曲名称
music_singer = i["artist"] # 歌手
music_rid = i["rid"] # 歌曲接口需求的rid
musicList.append([music_name, music_singer, music_rid])
for filename in os.listdir("E://"): # 创建文件夹
if filename == "music_Dowload":
break
else:
os.mkdir(download_Path)
music_url = "https://www.kuwo.cn/url?format=mp3&rid={}&response=url&type=convert_url3&br=128kmp3&from=web&t=1610524114404&httpsStatus=1&reqId=bceb0151-5573-11eb-8fe4-01a71bac8f98"
music_headers = {
"Accept": "application / json, text / plain, * / *",
"Accept - Encoding": "gzip, deflate, br",
"Accept - Language": "zh - CN, zh;q=0.9",
"Connection": "keep - alive",
"Cookie": "_ga = GA1.2.1568052841.1610455603;_gid = GA1.2.846961065.1610455603;_gat = 1;Hm_lvt_cdb524f42f0ce19b169a8071123a4797 = 1610455603, 1610524073;Hm_lpvt_cdb524f42f0ce19b169a8071123a4797 = 1610524073;kw_token = RCTLYWQZTWG",
"Host": "www.kuwo.cn",
"Referer": "https: // www.kuwo.cn / singer_detail / 111900",
"User - Agent": "Mozilla / 5.0(WindowsNT10.0;WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 70.0.3538.25Safari / 537.36Core / 1.70.3861.400QQBrowser / 10.7.4313.400",
}
for music in musicList:
try:
music_data = requests.get(url=music_url.format(music[2]), headers=music_headers).text
music_data = json.loads(music_data)
DowloadUrl = music_data["url"]
data = requests.get(DowloadUrl).content
with open(download_Path+music[0]+music[1]+".mp3", "wb") as f:
f.write(data)
print(f"歌曲名:{music[0]},歌手:{music[1]},下载成功!")
except:
print(f"歌曲名:{music[0]},歌手:{music[1]},下载失败!!!")
music_download()