咪咕音乐

import requests
import os
import json
import time

class miguMusic(object):
def init(self):
self.musicURL = 'https://m.music.migu.cn/migu/remoting/scr_search_tag'
'?rows={}&type=2&keyword={}&pgc=1'
self.singer = ""
self.totlePage = "0"
self.headers = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 '
'Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Mobile Safari/537.36',
'Referer':'https://m.music.migu.cn/v3/search'
}

def get_desk_p(self):
    return os.path.join(os.path.expanduser('~'), "Desktop")

def getSinger(self):
    while self.singer == "":
        self.singer = input("搜索音乐/歌单/歌手:")
    self.file_path = '{}/咪咕音乐/{}'.format(self.get_desk_p(),self.singer)

    while self.totlePage.isdigit() == False or self.totlePage <= '0':
        self.totlePage = input("输入要下载歌曲的总数量:")

def get_request_migu_music(self,url):
    respose = requests.get(url=url,headers=self.headers)
    if respose.status_code == 200:
        music_json = json.loads(respose.content.decode())
        musics = music_json['musics']
        music_list = []
        for item in musics:
            if str(item['mp3']) != 'None':
                music_dict = {}
                music_dict['songName'] = item['songName']
                music_dict['mp3'] = item['mp3']
                music_list.append(music_dict)
        return music_list

def down_migu_misic(self,musics):
    for music_item in musics:
        music_url = str(music_item['mp3'])
        music_title = str(music_item['songName'])
        if len(music_url) != 0:
            respose = requests.get(music_url)
            if respose.status_code == 200:
                data = respose.content
                try:
                    if not os.path.exists(self.file_path):
                        print('文件夹', self.file_path, '不存在,重新建立')
                        os.makedirs(self.file_path)

                    # 获得音频后缀
                    # file_suffix = os.path.splitext(music_url)[1]
                    # 拼接音频名(包含路径)
                    filename = '{}/{}.mp3'.format(self.file_path,
                                                 music_title)
                    print('\n')
                    print('*******************************************')
                    print('……………………【{}】歌曲正在下载中 ……………………'.format(music_title))
                    print('*******************************************')
                    with open(filename, 'wb')as f:
                        f.write(data)
                        time.sleep(2)

                except IOError as e:
                    print('文件操作失败:' + e)
                except Exception as e:
                    print('错误:' + e)

def run_migu_misic(self):
    self.getSinger()
    lists = self.get_request_migu_music(self.musicURL.format(self.totlePage,self.singer))
    self.down_migu_misic(lists)

if name == 'main':
miguMusic().run_migu_misic()

你可能感兴趣的:(咪咕音乐)