python實戰:不到50行的代碼讓你下載酷狗音樂任意版本的VIP歌曲

**1、**此處以下載《周杰倫—等你下課》爲目標歌曲,首先我們來到酷狗音樂網頁版:https://www.kugou.com/yy/html/search.html#searchType=song&searchKeyWord=等你下課 ,搜索到目標歌曲有許多版本。點擊第一首來到播放頁面,如下圖操作打開chrome的開發者工具後切換到Network,重新刷新頁面,找到請求到這首歌曲播放源的URL。
在這裏插入圖片描述
從上面可以看到這首歌曲播放源的URL爲play_url的值,切換到Headers中可以看到請求的URL爲:https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19105183192177131513_1551168792939&hash=718567D263C17BB3945B596CDD887C27&album_id=8308163&_=1551168792940 ,爲了得到該URL的請求規律,我們將上面URL的某些參數進行刪除,看能否請求到正常的數據,經過測試發現其可以簡化爲:https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash=718567D263C17BB3945B596CDD887C27 ,可見我們只需得到歌曲對應的hash即可。

**2、**返回到搜索頁面,打開chrome的開發者工具後切換到Network,重新刷新頁面,找到請求到這些歌曲的URL,如下圖:
在這裏插入圖片描述
從上圖的Preview中可以看到有我們所需要的hash值,切換到Headers可以看到請求URL爲:https://songsearch.kugou.com/song_search_v2?callback=jQuery112406843776112652964_1551169279967&keyword=等你下課&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1551169279969 ,爲了得到該URL的請求規律,同理我們將上面URL的某些參數進行刪除,看能否請求到正常的數據,經過測試發現其可以簡化爲:https://songsearch.kugou.com/song_search_v2?keyword=等你下課&platform=WebFilter ,至此我們可以敲代碼了,以下是全部代碼。

from requests_html import HTMLSession
import urllib.request,os,json
from urllib.parse import quote
class KuGou():
    def __init__(self):
        self.get_music_url='https://songsearch.kugou.com/song_search_v2?keyword={}&platform=WebFilter'
        self.get_song_url='https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash={}'
        if not os.path.exists("d:/music"):
            os.mkdir('d:/music')

    def parse_url(self,url):
        session = HTMLSession()
        response = session.get(url)
        return response.content.decode()

    def get_music_list(self,keyword):
        music_dirt=json.loads(self.parse_url(self.get_music_url.format(quote(keyword))))
        music_list=music_dirt['data']['lists']
        song_list=[]
        for music in music_list:
            song_name=music['FileName'].replace("<\\/em>", "").replace("<em>", "")
            song_list.append({'hash':music['FileHash'], 'song_name':song_name})
            print(str(len(song_list))+'---'+song_name)
        return song_list

    def download(self,song):
        song_dirt=json.loads(self.parse_url(self.get_song_url.format(song['hash'])))
        download_url=song_dirt['data']['play_url']
        if download_url:
            try:
                # 根據音樂url地址,用urllib.request.retrieve直接將遠程數據下載到本地
                urllib.request.urlretrieve(download_url, 'd:/music/' + song['song_name'] + '.mp3')
                print('Successfully Download:' + song['song_name'] + '.mp3')
            except:
                print('Download wrong~')

if __name__ == '__main__':
    kugou=KuGou()
    while True:
	    keyword=input('請輸入要下載的歌曲名:')
	    print('-----------歌曲《'+keyword+'》的版本列表------------')
	    music_list=kugou.get_music_list(keyword)
	    song_num=input('請輸入要下載的歌曲序號:')
	    kugou.download(music_list[int(song_num)-1])

程序運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章