溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python怎么制作各大音樂平臺(tái)的聚合的音樂下載器

發(fā)布時(shí)間:2021-11-25 11:59:29 來源:億速云 閱讀:120 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“Python怎么制作各大音樂平臺(tái)的聚合的音樂下載器”,在日常操作中,相信很多人在Python怎么制作各大音樂平臺(tái)的聚合的音樂下載器問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”Python怎么制作各大音樂平臺(tái)的聚合的音樂下載器”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

轉(zhuǎn)載地址

https://blog.csdn.net/fei347795790?t=1

安裝

需要安裝一個(gè)輔助模塊 prettytable,用于美化控制臺(tái)的表格輸出

pip install prettytable

提取音樂鏈接

搜索音樂

以下載 QQ 音樂為例,在首頁(https://y.qq.com/) 上的搜索框中搜索 <<厚顏無恥>>, 打開 F12 的控制臺(tái)面板,可以找到如下圖的搜索鏈接,這個(gè)鏈接返回的是一個(gè)音樂列表的 json 串

Python怎么制作各大音樂平臺(tái)的聚合的音樂下載器

def get_request(self, url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
        }
        response = requests.get(url, headers = headers)
        if response.status_code == 200:
            return response
    except Exception as e:
        print("請(qǐng)求出錯(cuò):", e)
        
    return None

def search_music(self, key):
    # 20: 查詢 20 條數(shù)據(jù),key:關(guān)鍵字
    url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=1&n=%d&w=%s' % (20, key)
    resp = self.get_request(url)
    resp_json = json.loads(resp.text[9:][:-1])
    data_song_list = resp_json['data']['song']['list']
    song_list = []
    for song in data_song_list:
        singers = [s.get("name", "") for s in song.get("singer", "")]
        song_list.append({'name': song['songname'], 'songmid': song['songmid'], 'singer': '|'.join(singers)})

    return song_list

示例結(jié)果:

[{'name': '富士山下', 'songmid': '003dtkNk26WhJD', 'singer': '陳奕迅'}, {'name': '不要說話', 'songmid': '002B2EAA3brD5b', 'singer': '陳奕迅'}, ...., {'name': '最佳損友', 'songmid': '003hFxQh376Cv5', 'singer': '陳奕迅'}]

獲取下載鏈接

把音樂列表頁中的歌曲點(diǎn)擊到播放音樂的頁面,在控制面板找到多個(gè)以 m4a 結(jié)尾的音樂實(shí)際鏈接

Python怎么制作各大音樂平臺(tái)的聚合的音樂下載器

def download_url(self, song):
    guid = str(random.randrange(1000000000, 10000000000))

    purl_url = 'https://u.y.qq.com/cgi-bin/musicu.fcg?' \
                '&data={"req":{"param":{"guid":" %s"}},' \
                        '"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"%s","songmid":["%s"],"uin":"%s"}},"comm":{"uin":%s}}' \
                % (guid, guid, song['songmid'], 0, 0)

    resp = self.get_request(purl_url)

    if resp is None:
        return 'N', 'None', '.m4a'

    resp_json = json.loads(resp.text)

    purl = resp_json['req_0']['data']['midurlinfo'][0]['purl']

    # 有些音樂在網(wǎng)站上不能聽
    if len(purl) < 1:
        msg = 'N'

    download_url = 'http://ws.stream.qqmusic.qq.com/' + purl
    song_data = self.get_request(download_url)
    if song_data:
        msg = 'Y'
    return msg, download_url, '.m4a'

示例結(jié)果:

只有一個(gè)域名的地址的下載鏈接表示這個(gè)音樂只能在客戶端聽,網(wǎng)頁版聽不了

到這里已經(jīng)完了 QQ 音樂的搜索、抓取腳本,用同樣的方式抓取咪咕音樂(http://m.music.migu.cn)做成咪咕音樂腳本,咪咕音樂更容易爬取

命令行主界面

主界面的主要功能就是以表格的方式顯示搜索到的音樂和以序號(hào)的方式下載音樂

import os

from qqMusic import QQMusic
from miguMusic import MiGuMusic
from prettytable import PrettyTable


class MusicBox(object):

    def __init__(self):
        pass

    def download(self, data, songName, type):

        save_path = 'music/' + songName + '.' + type
        file = 'music'
        if os.path.exists(file):
            pass
        else:
            os.mkdir('music')

        try:
            print("{}下載中.....".format(songName), end='')
            with open(save_path, 'wb') as f:
                f.write(data)
            print("已下載完成")
        except Exception as err:
            print("文件寫入出錯(cuò):", err)
            return None

    def main(self):
        print('請(qǐng)輸入需要下載的歌曲或者歌手:')
        key = input()
        print('正在查詢..\033[32mQQ音樂\033[0m', end='')
        qqMusic = QQMusic()
        qq_song_list = qqMusic.main(key)
        print('...\033[31m咪咕音樂\033[0m')
        miguMusic = MiGuMusic()
        migu_song_list = miguMusic.main(key)

        qq_song_list.extend(migu_song_list)
        song_dict = {}
        for song in qq_song_list:
            key = song['name'] + '\\' + song['singer']
            s = song_dict.get(key)
            if s:
                if s['msg'] != 'Y':
                    song_dict[key] = song
            else:
                song_dict[key] = song

        i = 0

        table = PrettyTable(['序號(hào)', '歌手', '下載', '歌名'])
        table.border = 0
        table.align = 'l'
        for song in list(song_dict.values()):
            i = i + 1
            table.add_row([str(i), song['singer'], song['msg'], song['name']])
        print(table)

        while 1:
            print('\n請(qǐng)輸入需要下載,按 q 退出:')
            index = input()
            if index == 'q':
                return

            song = list(song_dict.values())[int(index) - 1]
            data = qqMusic.get_request(song['downloadUrl'])
            if song['msg'] == 'Y':
                self.download(data.content, song['name'], song['type'])
            else:
                print('該歌曲不允許下載')

if __name__ == '__main__':
    musicBox = MusicBox()
    musicBox.main()

到此,關(guān)于“Python怎么制作各大音樂平臺(tái)的聚合的音樂下載器”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI