625 views
Python开发 / python爬虫

Python爬取QQ音乐

文章目录

爬取QQ音乐并下载

#!/usr/bin/env python
#coding:utf8
#++++++++++++description++++++++++++#
"""
@author:ying
@contact:1074020480@qq.com
@python3 
@software: PyCharm
@file: QQ_music.py
@time: 2019-11-13 14:18:23
"""
#+++++++++++++++++++++++++++++++++++#
import requests,os,re,json,urllib
dir_name=os.getcwd()+'/music_file/'
if not os.path.exists(dir_name):
    os.mkdir(dir_name)


class DownloadMusic(object):
    def __init__(self):
        self.get_music_url = 'https://u.y.qq.com/cgi-bin/musicu.fcg?data={"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"602087500","songmid":["%s"],"songtype":[0],"uin":"0","loginflag":1,"platform":"20"}},"comm":{"uin":0,"format":"json","ct":24,"cv":0}}'

    def get_music_list(self,music_name):
        get_music_list_url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?new_json=1&remoteplace=txt.yqq.song&t=0&aggr=2&cr=2&w={0}&format=json&platform=yqq.json'.format(music_name)
        r = requests.get(get_music_list_url)
        js_content = json.loads(r.content)
        music_list = js_content['data']['song']['list']
        song_list = []
        for music in music_list:
            sing_name = music['singer'][0]['name']
            song_name = music['title_hilight'].replace(r"</em>", "").replace("<em>", "")
            song_list.append({'songmid': music['mid'], 'singer': sing_name, 'song_name': song_name})
            print(str(len(song_list)) + '、' + sing_name + '--' + song_name)
            with open('music_list.text','w') as f:
                f.write(json.dumps(song_list))
        return song_list
    def down_music(self,song_num):
        with open('music_list.text','r') as f:
            song_list=json.loads(f.read())
            # print(song_list)
        # song_list=self.get_music_list()
        # song_num=input('请输入要下载的歌曲序号:')
        if song_num.isdigit():
            song = song_list[int(song_num) - 1]
            song_dirt = json.loads(requests.get(self.get_music_url % song['songmid']).content)
            d_url = song_dirt["req_0"]["data"]["midurlinfo"][0]["purl"]
            download_url = 'http://dl.stream.qqmusic.qq.com/'+ d_url
        else:
            print('请输入数字,谢谢!')
            exit()
        if d_url:
            try:
                print('正在下载...')
                # 根据音乐url地址,用urllib.request.retrieve直接将远程数据下载到本地
                urllib.request.urlretrieve(download_url, dir_name + song['song_name'] + '.mp3')
                print('恭喜你,下载歌曲成功:' + song['singer'] + '--' + song['song_name'] + '.mp3')
            except:
                print('sorry,下载失败')
        else:
            print('没有找到该音乐的下载地址,请下载其他的版本...')


# DownloadMusic().get_music_list(music_name='张杰')
# DownloadMusic().down_music()


try:
    while True:
        keyword = input('-----------温馨提示:[q/Q/exit->退出程序]-----------\n请输入歌曲/歌手名:')
        quit_code=['q','Q','退出','exit']
        if not keyword in  quit_code:
            print('-----------歌曲/歌手《' + keyword + '》的版本列表-----------')
            music_list = DownloadMusic().get_music_list(music_name='{0}'.format(keyword))
            song_num = input('-----------温馨提示:[q/Q/exit->返回上一层]-----------\n请输入要下载的歌曲序号:')
            if song_num not in quit_code:
                DownloadMusic().down_music(song_num)
            else:
                continue
        else:
            print('已退出')
            exit()
except KeyboardInterrupt:
    print('\n已手动关闭程序')
    exit()
-------------------------结果---------------------------------
-----------温馨提示:[q/Q/exit->退出程序]-----------
请输入歌曲/歌手名:ll
-----------歌曲/歌手《ll》的版本列表-----------
1、MC语音表哥--LL (伴奏)
2、杨宗纬--凉凉
3、张碧晨--凉凉 (Live)
4、Stevie Hoang--I'll Be Fine
5、Klan--Ll (Explicit)
6、Justin Bieber--I'll Show You
7、红桃老K--LL
8、冯提莫--凉凉
9、丛瑞--凉凉
10、杨宗纬--凉凉 (Live)
-----------温馨提示:[q/Q/exit->返回上一层]-----------
请输入要下载的歌曲序号:3
正在下载...
恭喜你,下载歌曲成功:张碧晨--凉凉 (Live).mp3
-----------温馨提示:[q/Q/exit->退出程序]-----------
影子专属博客 赣ICP备17013143号