用于下载网易云歌单里所有音乐,可通过crontab定时同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# -*- coding:utf-8 -*-
import requests
import re
import traceback
import sys
import subprocess
import time
import os

class netease():
def __init__(self,path,*args):
if os.path.exists(path) == False:
os.mkdir(path)
self.path = path
# 文件重下计数,防止无限下载
self.num=0
self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0'}
for j in args:
ids,names = self.getIdNames(j)
if ids!=None and names!=None:
for i in range(len(ids)):
for k in range(5):
s = self.download(ids[i],names[i])
if s:
break
print(names[i]+' 下载失败,正在重试第'+str(k+1)+'次...\n')
"""
获取所有id和名字
"""
def getIdNames(self,sid):
rq = requests.get(('https://music.163.com/playlist?id=%s' % sid),headers=self.headers)
if rq.status_code == 200:
rq.encoding='utf-8'
html = rq.text.replace('\r','').replace('\n','').replace('\t','').replace('\xa0',' ').replace('\u3000',' ')
# 取出播放列表
playlist = re.compile(r'(?<=id\=\"song-list-pre-cache\").*?(?=\<textarea)')
playlist2 = re.compile(r'(?<=\<ul class\=\"f-hide\"\>).*?(?=\<\/ul\>)')
# 取出音乐id
id_re = re.compile(r'(?<=song\?id=).*?(?=\")')
# 取出音乐名字
name_re = re.compile(r'(?<=\">).*?(?=\<\/a\>)')

tbody1 = re.findall(playlist,html)
tbody = re.findall(playlist2,str(tbody1))
if len(tbody)>0:
ids = re.findall(id_re,tbody[0])
names = re.findall(name_re,tbody[0])
return ids,names
return None,None
pass
def download(self,mid,name):
name_re = re.compile(r'[\\s\\\\/:\\*\\?\\\"<>\\|]')
newname = name_re.sub('',name)
filepath = self.path+'/'+newname+'.mp3'
# 判断文件是否存在
if os.path.isfile(filepath)== False:
req = requests.get('http://music.163.com/song/media/outer/url?id=%s' % mid)
if req.status_code == 200:
if len(req.content) <= 1048576:
time.sleep(3)
return False
f = open(filepath,'wb')
f.write(req.content)
#print('下载成功:',name+'.mp3')
f.close()
time.sleep(1)
return True

if __name__ == '__main__':
# 路径及歌单id
net = netease('/root/music','2164388330','2164366660')
pass