Created
March 18, 2015 06:51
-
-
Save wong2/1dc60b73e8ca44b85f36 to your computer and use it in GitHub Desktop.
下载网易云音乐歌单
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*-coding:utf-8-*- | |
import os | |
import re | |
import sys | |
import requests | |
from gevent import monkey | |
monkey.patch_all() | |
from gevent.pool import Pool | |
def norm_name(name): | |
'''turn a string into valid file name''' | |
return re.sub(' |/', '_', name) | |
def get_songs_by_playlist(playlist_id): | |
url = 'http://music.163.com/api/playlist/detail?id={}'.format(playlist_id) | |
r = requests.get(url) | |
resp = r.json() | |
assert resp['code'] == 200 | |
return [(track['name'], track['mp3Url']) for track in resp['result']['tracks']] | |
def download_song(song): | |
name, mp3_url = song | |
print 'Downloading ', name, mp3_url | |
filename = u'{}.mp3'.format(norm_name(name)) | |
r = requests.get(mp3_url, stream=True) | |
with open(filename, 'wb') as f: | |
for chunk in r.iter_content(chunk_size=1024): | |
if chunk: | |
f.write(chunk) | |
f.flush() | |
def download_palylist(playlist_id): | |
if not os.path.exists(playlist_id): | |
os.makedirs(playlist_id) | |
os.chdir(playlist_id) | |
songs = get_songs_by_playlist(playlist_id) | |
pool = Pool(10) | |
pool.map(download_song, songs) | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print 'Usage: python downlist.py [playlist_id]' | |
else: | |
download_palylist(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment