首页 技术 正文
技术 2022年11月15日
0 收藏 768 点赞 4,234 浏览 1699 个字

一、目标:

  下载网易云音乐热门歌单

二、用到的模块:

  requests,multiprocessing,re。

三、步骤:

  (1)页面分析:首先打开网易云音乐,选择热门歌单,可以看到以下歌单列表,然后打开开发者工具

【Python3爬虫】网易云音乐歌单下载

【Python3爬虫】网易云音乐歌单下载

   因此我们需要请求的url就是https://music.163.com/discover/playlist,然后用requests.get()方法请求页面,对于返回的结果,用正则表达式进行解析,得到歌单名字和歌单id,解析的正则表达式如下:

res = requests.get(url, headers=headers)
data = re.findall('<a title="(.*?)" href="/playlist\?id=(\d+)" rel="external nofollow" rel="external nofollow" class="msk"></a>', res.text)

  

  (2)得到歌单名字和歌单id后,构造歌单的url,然后模仿步骤(1)可以得到歌曲名字和歌曲id,解析的正则表达式如下:

re.findall(r'<a href="/song\?id=(\d+)" rel="external nofollow"  rel="external nofollow" >(.*?)</a>', res.text)

  再得到歌曲id后,构造歌曲的url,然后用requests.get().content方法下载歌曲,歌曲的url构造方法如下:

"http://music.163.com/song/media/outer/url?id=%s" %(歌曲id)

  (3)由于部分歌曲的名字并不能作为文件名保存下来,所以用到了try…except,对于不能保存为文件名的歌曲,我选择pass掉==

    

  (4)因为要下载多个歌单,一个歌单里又有很多歌曲,所以用到了multiprocessing模块的Pool方法,提高程序运行的效率。

四、具体代码

  因为下载所有歌单会需要很长时间,所以我们先下载前三个歌单试试==

 import requests
import re
from multiprocessing import Pool headers = {
'Referer': 'https://music.163.com/',
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 "
"Safari/537.36"
} def get_page(url):
res = requests.get(url, headers=headers)
data = re.findall('<a title="(.*?)" href="/playlist\?id=(\d+)" rel="external nofollow" rel="external nofollow" class="msk"></a>', res.text) pool = Pool(processes=4)
pool.map(get_songs, data[:3])
print("下载完毕!") def get_songs(data):
playlist_url = "https://music.163.com/playlist?id=%s" % data[1]
res = requests.get(playlist_url, headers=headers)
for i in re.findall(r'<a href="/song\?id=(\d+)" rel="external nofollow" rel="external nofollow" >(.*?)</a>', res.text):
download_url = "http://music.163.com/song/media/outer/url?id=%s" % i[0]
try:
with open('music/' + i[1]+'.mp3', 'wb') as f:
f.write(requests.get(download_url, headers=headers).content)
except FileNotFoundError:
pass
except OSError:
pass if __name__ == '__main__':
hot_url = "https://music.163.com/discover/playlist/?order=hot"
get_page(hot_url)

五、运行结果

【Python3爬虫】网易云音乐歌单下载

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,488
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289