Skip to content

Instantly share code, notes, and snippets.

@wong2 wong2/downlist.py
Created Mar 18, 2015

Embed
What would you like to do?
下载网易云音乐歌单
#-*-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
You can’t perform that action at this time.