手机网易云批量下载音乐,Python下载音乐
python视频教程栏目介绍实现下载免费音乐
相关免费学习推荐:python视频教程
运行效果
代码
# -*-编码:utf-8 -*-
导入请求,hashlib,sys,click,re,base64,binascii,json,os
来自密码.密码导入俄歇电子能谱
从超文本传送协议(Hyper Text Transport Protocol的缩写)导入库克耶尔
Website:http://cuijiahua.com
作者:杰克崔
Refer:https://github.com/darknessomi/musicbox
class Encrypyed():
解密算法
def __init__(self):
自我。module= 00 e0b 509 f 6259 df 8642 DBC 35662901477 df 22677 EC 152 b5 ff 68 ace 615 bb7b 725152 B3 ab 17 a 876 ea 8 a5 aa 76 D2 e 417629 EC 4 ee 341 f 56135 fccf 695280104 e 0312 ecbda 92557 c 93870114 af
self.nonce=0CoJUm6Qyw8W8jud
self.pub_key=010001
# 登录加密算法,基于https://github.com/stkevintan/nw_musicbox脚本实现
定义加密请求(自身,文本):
text=json.dumps(text)
sec _ key=self。创建密钥(16)
enc _ text=self。AES _ encrypt(self。AES _ encrypt(text,self.nonce),sec_key.decode(utf-8 ))
enc _ sec _ key=self。RSA _ encr pt(sec _ key,self.pub_key,self.modulus)
data={params: enc_text, encSecKey: enc_sec_key}
返回数据
def aes_encrypt(self,text,secKey):
pad=16透镜(文本)% 16
text=text chr(pad) * pad
加密器=AES。新(秒键。编码( utf-8 )、AES .模式_CBC,b0102030405060708 )
密文=加密机。加密(文本。编码( utf-8 ))
密文=base64.b64encode(密文)。解码(“utf-8”)
返回密文
def rsa_encrpt(self,text,pubKey,module):
text=text[:-1]
RS=pow(int(binascii。hexlify(文本),16),int(公钥,16),int(模数,16))
返回格式(rs, x ).零填充(256)
def create_secret_key(self,size):
返回比纳斯CII。hexlify(OS。urandom(size))[:16]
班歌():
歌曲对象,用于存储歌曲的信息
def __init__(self,song_id,song_name,song_num,song _ url=无):
self.song_id=song_id
self.song_name=song_name
self.song_num=宋_num
self.song_url= 如果歌曲_网址不是其他歌曲_网址
英语字母表中第三个字母
lass Crawler():
"""
网易云爬取API
"""
def __init__(self, timeout=60, cookie_path='.'):
self.headers = {
'Accept': '*/*',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'music.163.com',
'Referer': 'http://music.163.com/search/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
self.session = requests.Session()
self.session.headers.update(self.headers)
self.session.cookies = cookiejar.LWPCookieJar(cookie_path)
self.download_session = requests.Session()
self.timeout = timeout
self.ep = Encrypyed()
def post_request(self, url, params):
"""
Post请求
:return: 字典
"""
data = self.ep.encrypted_request(params)
resp = self.session.post(url, data=data, timeout=self.timeout)
result = resp.json()
if result['code'] != 200:
click.echo('post_request error')
else:
return result
def search(self, search_content, search_type, limit=9):
"""
搜索API
:params search_content: 搜索内容
:params search_type: 搜索类型
:params limit: 返回结果数量
:return: 字典.
"""
url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='
params = {'s': search_content, 'type': search_type, 'offset': 0, 'sub': 'false', 'limit': limit}
result = self.post_request(url, params)
return result
def search_song(self, song_name, song_num, quiet=True, limit=9):
"""
根据音乐名搜索
:params song_name: 音乐名
:params song_num: 下载的歌曲数
:params quiet: 自动选择匹配最优结果
:params limit: 返回结果数量
:return: Song独享
"""
result = self.search(song_name, search_type=1, limit=limit)
if result['result']['songCount'] <= 0:
click.echo('Song {} not existed.'.format(song_name))
else:
songs = result['result']['songs']
if quiet:
song_id, song_name = songs[0]['id'], songs[0]['name']
song = Song(song_id=song_id, song_name=song_name, song_num=song_num)
return song
def get_song_url(self, song_id, bit_rate=320000):
"""
获得歌曲的下载地址
:params song_id: 音乐ID<int>.
:params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000}
:return: 歌曲下载地址
"""
url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
csrf = ''
params = {'ids': [song_id], 'br': bit_rate, 'csrf_token': csrf}
result = self.post_request(url, params)
# 歌曲下载地址
song_url = result['data'][0]['url']
# 歌曲不存在
if song_url is None:
click.echo('Song {} is not available due to copyright issue.'.format(song_id))
else:
return song_url
def get_song_by_url(self, song_url, song_name, song_num, folder):
"""
下载歌曲到本地
:params song_url: 歌曲下载地址
:params song_name: 歌曲名字
:params song_num: 下载的歌曲数
:params folder: 保存路径
"""
if not os.path.exists(folder):
os.makedirs(folder)
fpath = os.path.join(folder, str(song_num) + '_' + song_name + '.mp3')
if sys.platform == 'win32' or sys.platform == 'cygwin':
valid_name = re.sub(r'[<>:"/\\?*]', '', song_name)
if valid_name != song_name:
click.echo('{} will be saved as: {}.mp3'.format(song_name, valid_name))
fpath = os.path.join(folder, str(song_num) + '_' + valid_name + '.mp3')
if not os.path.exists(fpath):
resp = self.download_session.get(song_url, timeout=self.timeout, stream=True)
length = int(resp.headers.get('content-length'))
label = 'Downloading {} {}kb'.format(song_name, int(length/1024))
with click.progressbar(length=length, label=label) as progressbar:
with open(fpath, 'wb') as song_file:
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
song_file.write(chunk)
progressbar.update(1024)
class Netease():
"""
网易云音乐下载
"""
def __init__(self, timeout, folder, quiet, cookie_path):
self.crawler = Crawler(timeout, cookie_path)
self.folder = '.' if folder is None else folder
self.quiet = quiet
def download_song_by_search(self, song_name, song_num):
"""
根据歌曲名进行搜索
:params song_name: 歌曲名字
:params song_num: 下载的歌曲数
"""
try:
song = self.crawler.search_song(song_name, song_num, self.quiet)
except:
click.echo('download_song_by_serach error')
# 如果找到了音乐, 则下载
if song != None:
self.download_song_by_id(song.song_id, song.song_name, song.song_num, self.folder)
def download_song_by_id(self, song_id, song_name, song_num, folder='.'):
"""
通过歌曲的ID下载
:params song_id: 歌曲ID
:params song_name: 歌曲名
:params song_num: 下载的歌曲数
:params folder: 保存地址
"""
try:
url = self.crawler.get_song_url(song_id)
# 去掉非法字符
song_name = song_name.replace('/', '')
song_name = song_name.replace('.', '')
self.crawler.get_song_by_url(url, song_name, song_num, folder)
except:
click.echo('download_song_by_id error')
if __name__ == '__main__':
timeout = 60
output = 'Musics'
quiet = True
cookie_path = 'Cookie'
netease = Netease(timeout, output, quiet, cookie_path)
music_list_name = 'music_list.txt'
# 如果music列表存在, 那么开始下载
if os.path.exists(music_list_name):
with open(music_list_name, 'r') as f:
music_list = list(map(lambda x: x.strip(), f.readlines()))
for song_num, song_name in enumerate(music_list):
netease.download_song_by_search(song_name,song_num + 1)
else:
click.echo('music_list.txt not exist.')
相关免费学习推荐:php编程(视频)以上就是实现python批量下载网易云音乐的免费音乐的详细内容,更多请关注盛行IT软件开发工作室其它相关文章!
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。