# -*- coding: utf-8 -*-
"""
1.先media,再xhr
2.url:http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key=%E8%96%9B%E4%B9%8B%E8%B0%A6&pn=1&rn=30&reqId=995207e0-62c9-11ea-9542-49afad2eecb6".format(singer,)
3.发送请求,第三方库,如安装 pip install requests
4.提取数据,写代码时,再好封装
"""
import requests

headers={
        "User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36",
        "Referer": "http://www.kuwo.cn/search/list?key=%E8%96%9B%E4%B9%8B%E8%B0%A6",#从哪里来
        "csrf":"TQJ0RC6WH0O",#表单验证,令牌,暗号token
        "Cookie":"Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1583842299; _ga=GA1.2.1842872849.1583842300; _gid=GA1.2.11466405.1583842300; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1583842814; _gat=1; kw_token=TQJ0RC6WH0O"
        
        }

def get_music(rid,name):
    #在hxr中找
    url="http://www.kuwo.cn/url?format=mp3&rid={}&response=url&type=convert_url3&br=128kmp3&from=web&t=1583846010210&reqId=efae2b31-62d0-11ea-be08-dd412ee8e242".format(rid)
    result=requests.get(url,headers=headers).json()
    music_url=result["url"]
    with open("酷我音乐/{}.mp3".format(name),"wb") as f:
        music=requests.get(music_url).content
        f.write(music)
        print("over")
        

def main():
    singer=input("输入你要的歌手:(关晓彤)")
    number=int(input("你的页数"))
    
    for x in range(1,number+1):
        url="http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={}&pn={}&rn=30&reqId=995207e0-62c9-11ea-9542-49afad2eecb6".format(singer,x)
        response=requests.get(url,headers=headers).json()
        #print(response.text)
        data=response["data"]["list"]
        #print(data)
        for i in data:
            rid=i["rid"]#在字典中取值
            name=i["name"]
            print(rid,name)
            get_music(rid,name)
main()