1. 程式人生 > 其它 >爬取網易雲音樂熱歌榜 - Python

爬取網易雲音樂熱歌榜 - Python

現在很多音樂平臺的音樂因為版權,或多或少要收費或者只對vip開放,有時候想聽首自己喜歡的歌都很鬧心。今天來爬下網易雲音樂的熱歌榜,也可以爬自己喜歡的音樂然後下載到本地進行欣賞。

"""
    Python爬取網易雲音樂熱歌榜
"""
import requests
import re
import os


filePath = 'music\\'

if not os.path.exists(filePath):
    os.mkdir(filePath)

url = 'https://music.163.com/discover/toplist?id=3778678' # 熱歌榜的url

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36',
}

response = requests.get(url, headers=headers)
# print(response.text)

# 用正則表示式在網頁內容中查詢我們需要的內容
allMusicData = re.findall('<a href="/song\?id=(\d+)">(.*?)</a>', response.text)
# print(allMusicData) # 列表,列表的元素為元組

for musicId, musicName in allMusicData: #  迴圈讀取
    musicUrlForDownLoad = f'https://music.163.com/song/media/outer/url?id={musicId}.mp3' # 只要獲取到了id,可以下載任何音樂
    print(musicId, musicName) # 列印下
    musicContent = requests.get(musicUrlForDownLoad, headers=headers).content
    # 讀取到了就開始儲存
    with open(filePath + musicName + '.mp3', mode='wb') as f:
        f.write(musicContent)

 

下載到本地就可以盡情的聆聽了。