import requests
from lxml import etree
import json
import re
import time


class kugou():

    def startkugou(self):
        for i in range(23, 24):
            print(i)
            res = requests.get('https://www.kugou.com/yy/rank/home/%s-8888.html?from=rank' % str(i), verify=False)
            # print(res.text)
            self.get_song(res)

    def get_song(self, res):
        html = etree.HTML(res.content.decode('utf8'))
        # print(html, '-------------')
        content = html.xpath('//script[11]')
        # print(content[0])
        content2 = content[0].text
        # 解析出json列表，类型是str
        content1 = content2.split('global.features =')[1].split('(function()')[0].strip()[0:-1]
        try:
            # 转换成json数据
            content = json.loads(content1)
            for i in range(len(content)):
                # print(content[i], '-------------------')
                hash = content[i]["Hash"]
                album_id = content[i]["album_id"]
                file_name = content[i]["FileName"]
                url = f'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash={hash}&album_id={album_id}&dfid=3w04aT3Gbgut0e6MAN2y6uWb&mid=c5895e913353ead095d4539da6974010&platid=4&_={int(time.time() * 1000)}'
                # 获取歌曲信息中的play_url
                hash_content = requests.get(url, verify=False).json()
                print(hash_content, '-')
                data = hash_content.get('data')
                if data:
                    play_url = data.get('play_url', '')
                    print(f'文件名：{file_name}, 播放地址：{play_url}')
                    with open('kugou/' + file_name + ".mp3", "wb")as fp:
                        fp.write(requests.get(play_url, verify=False).content)



        except json.decoder.JSONDecodeError as e:
            print(e)
            print(content2)
            content1 = content2.split('global.features =')[1].strip().split('(function() {')[0].strip()
            content1 = content1[0:-1]
            print(content1)

    def validateTitle(self, file_name):
        """ 将 title 名字 规则化
        :param title: title name 字符串
        :return: 文件命名支持的字符串
        """
        rstr = r"[\=\(\)\,\/\\\:\*\?\"\<\>\|\' ']"  # '= ( ) ， / \ : * ? " < > |  '   还有空格
        new_title = re.sub(rstr, "_", file_name)  # 替换为下划线
        return new_title

if __name__ == '__main__':
    kugou().startkugou()
