欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 根據(jù)列表批量下載網(wǎng)易云音樂的免費(fèi)音樂

 更新時(shí)間:2020年12月03日 17:22:00   投稿:yxs  
這篇文章主要介紹了python 根據(jù)列表下載網(wǎng)易云音樂的免費(fèi)音樂,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下

運(yùn)行效果

代碼

# -*- coding:utf-8 -*-
import requests, hashlib, sys, click, re, base64, binascii, json, os
from Crypto.Cipher import AES
from http import cookiejar

"""
Website:http://cuijiahua.com
Author:Jack Cui
Refer:https://github.com/darknessomi/musicbox
"""

class Encrypyed():
	"""
	解密算法
	"""
	def __init__(self):
		self.modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
		self.nonce = '0CoJUm6Qyw8W8jud'
		self.pub_key = '010001'

	# 登錄加密算法, 基于https://github.com/stkevintan/nw_musicbox腳本實(shí)現(xiàn)
	def encrypted_request(self, text):
		text = json.dumps(text)
		sec_key = self.create_secret_key(16)
		enc_text = self.aes_encrypt(self.aes_encrypt(text, self.nonce), sec_key.decode('utf-8'))
		enc_sec_key = self.rsa_encrpt(sec_key, self.pub_key, self.modulus)
		data = {'params': enc_text, 'encSecKey': enc_sec_key}
		return data

	def aes_encrypt(self, text, secKey):
		pad = 16 - len(text) % 16
		text = text + chr(pad) * pad
		encryptor = AES.new(secKey.encode('utf-8'), AES.MODE_CBC, b'0102030405060708')
		ciphertext = encryptor.encrypt(text.encode('utf-8'))
		ciphertext = base64.b64encode(ciphertext).decode('utf-8')
		return ciphertext

	def rsa_encrpt(self, text, pubKey, modulus):
		text = text[::-1]
		rs = pow(int(binascii.hexlify(text), 16), int(pubKey, 16), int(modulus, 16))
		return format(rs, 'x').zfill(256)

	def create_secret_key(self, size):
		return binascii.hexlify(os.urandom(size))[:16]


class Song():
	"""
	歌曲對(duì)象,用于存儲(chǔ)歌曲的信息
	"""
	def __init__(self, song_id, song_name, song_num, song_url=None):
		self.song_id = song_id
		self.song_name = song_name
		self.song_num = song_num
		self.song_url = '' if song_url is None else song_url

class Crawler():
	"""
	網(wǎng)易云爬取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請(qǐng)求
		: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: 搜索內(nèi)容
		:params search_type: 搜索類型
		:params limit: 返回結(jié)果數(shù)量
		: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):
		"""
		根據(jù)音樂名搜索
		:params song_name: 音樂名
		:params song_num: 下載的歌曲數(shù)
		:params quiet: 自動(dòng)選擇匹配最優(yōu)結(jié)果
		:params limit: 返回結(jié)果數(shù)量
		:return: Song獨(dú)享
		"""

		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: 下載的歌曲數(shù)
		: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():
	"""
	網(wǎng)易云音樂下載
	"""
	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):
		"""
		根據(jù)歌曲名進(jìn)行搜索
		:params song_name: 歌曲名字
		:params song_num: 下載的歌曲數(shù)
		"""

		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: 下載的歌曲數(shù)
		: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.')

以上就是python 根據(jù)列表批量下載網(wǎng)易云音樂的免費(fèi)音樂的詳細(xì)內(nèi)容,更多關(guān)于python 網(wǎng)易云音樂下載的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python將excel轉(zhuǎn)換為csv的代碼方法總結(jié)

    python將excel轉(zhuǎn)換為csv的代碼方法總結(jié)

    在本篇文章里小編給大家分享了關(guān)于python如何將excel轉(zhuǎn)換為csv的實(shí)例方法和代碼內(nèi)容,需要的朋友們學(xué)習(xí)下。
    2019-07-07
  • python中實(shí)現(xiàn)修改圖像分辨率大小

    python中實(shí)現(xiàn)修改圖像分辨率大小

    這篇文章主要介紹了python中實(shí)現(xiàn)修改圖像分辨率大小問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • pytorch 自定義卷積核進(jìn)行卷積操作方式

    pytorch 自定義卷積核進(jìn)行卷積操作方式

    今天小編就為大家分享一篇pytorch 自定義卷積核進(jìn)行卷積操作方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • OpenCV搞定騰訊滑塊驗(yàn)證碼的實(shí)現(xiàn)代碼

    OpenCV搞定騰訊滑塊驗(yàn)證碼的實(shí)現(xiàn)代碼

    這篇文章主要介紹了OpenCV搞定騰訊滑塊驗(yàn)證碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • Python生成驗(yàn)證碼、計(jì)算具體日期是一年中的第幾天實(shí)例代碼詳解

    Python生成驗(yàn)證碼、計(jì)算具體日期是一年中的第幾天實(shí)例代碼詳解

    這篇文章主要介紹了Python生成驗(yàn)證碼、計(jì)算具體日期是一年中的第幾天,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Python操作Excel數(shù)據(jù)的封裝函數(shù)分享

    Python操作Excel數(shù)據(jù)的封裝函數(shù)分享

    對(duì)比其它編程語言,我們都知道Python最大的優(yōu)勢(shì)是代碼簡(jiǎn)單,有豐富的第三方開源庫供開發(fā)者使用。而對(duì)于數(shù)據(jù)的讀取和存儲(chǔ),對(duì)于普通人來講,除了數(shù)據(jù)庫之外,最常見的就是微軟的Excel。本文為大家準(zhǔn)備了Python操作Excel數(shù)據(jù)的封裝函數(shù),希望對(duì)大家有所幫助
    2022-11-11
  • 用python批量下載apk

    用python批量下載apk

    這篇文章主要介紹了用python批量下載apk的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-12-12
  • Python模擬隨機(jī)游走圖形效果示例

    Python模擬隨機(jī)游走圖形效果示例

    這篇文章主要介紹了Python模擬隨機(jī)游走圖形效果,涉及Python隨機(jī)數(shù)概率運(yùn)算及圖形繪制相關(guān)操作技巧,需要的朋友可以參考下
    2018-02-02
  • Spring Boot中使用IntelliJ IDEA插件EasyCode一鍵生成代碼詳細(xì)方法

    Spring Boot中使用IntelliJ IDEA插件EasyCode一鍵生成代碼詳細(xì)方法

    這篇文章主要介紹了Spring Boot中使用IntelliJ IDEA插件EasyCode一鍵生成代碼詳細(xì)方法,需要的朋友可以參考下
    2020-03-03
  • 如何在python中使用selenium的示例

    如何在python中使用selenium的示例

    這篇文章主要介紹了如何在python中使用selenium的示例,selenium提供了一個(gè)通用的接口,可模擬用戶來操作瀏覽器,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-12-12

最新評(píng)論