现在很多音乐平台的音乐因为版权,或多或少要收费或者只对vip开放,有时候想听首自己喜欢的歌都很闹心。今天来爬下网易云音乐的热歌榜,也可以爬自己喜欢的音乐然后下载到本地进行欣赏。
""" Python爬取网易云音乐热歌榜 """ import requests import re import os filePath = 'music\' if not os.path.exists(filePath): os.mkdir(filePath) url = 'https://music.xxx.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.xxx.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)
下载到本地就可以尽情的聆听了。