Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zz/5149963 to your computer and use it in GitHub Desktop.
Save zz/5149963 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
import re, sys, os, urllib
re_songs = re.compile(r'\'sid\': \'(.+?)\', \'sname\': \'(.+?)\'')
re_name = re.compile(r'\\&.+?;')
template_wgets = 'wget -nv -c -O "%s" %s'
durl = 'http://yinyueyun.baidu.com/data/cloud/downloadsongfile\?songIds\=%s\&rate\=320'
def modified_sname(sname):
sname = sname.replace('\\'', '\'')
sname = sname.replace(''', '\'')
sname = sname.replace('\\’', '\'')
sname = sname.replace('’', '\'')
sname = re_name.sub(r' - ', sname) # remove all http symbol from song-name.
sname = sname.replace('/', ' - ')
if len(sname) >= 250:
return sname[:243] + '...mp3'
else:
return sname
def down_album(albumid):
f = urllib.urlopen('http://music.baidu.com/album/' + albumid).read()
infos = re_songs.findall(f)
size = len(infos)
z = 0
if size <= 9:
z = 1
elif size >= 10 and size <= 99:
z = 2
elif size >= 100 and size <= 999:
z = 3
else:
z = 1
for i in range(1, size + 1):
songid, sname = infos[i - 1]
sname = str(i).zfill(z) + '.' + sname.strip() + '.mp3'
sname = modified_sname(sname)
wget = template_wgets % (sname, durl % songid)
status = os.system(wget)
if status == 2048: # 320kbps-mp3 is not available, so getting 192kbps-mp3.
wget = template_wgets % (sname, (durl[:-3] + '192') % songid)
status = os.system(wget)
if status == 2048: # 320kbps-mp3 is not available, so getting 128kbps-mp3.
wget = template_wgets % (sname, (durl[:-3] + '128') % songid)
status = os.system(wget)
if status not in [0, 2048]: # other http-errors, such as 302.
print '\n\n ----### ERROR ==> %d ###--- \n\n' % status
break
def down_song(songids):
for songid in songids:
f = urllib.urlopen('http://music.baidu.com/song/' + songid).read()
infos = re.search(r'\'sid\': \'%s\', \'sname\': \'(.+?)\'' % songid, f)
try:
sname = infos.group(1)
except:
infos = re.search(r'<span class="name">(.+?)</span>', f)
sname = infos.group(1)
sname = sname.strip() + '.mp3'
sname = modified_sname(sname)
wget = template_wgets % (sname, durl % songid)
status = os.system(wget)
if status == 2048: # 320kbps-mp3 is not available, so getting 192kbps-mp3.
wget = template_wgets % (sname, (durl[:-3] + '192') % songid)
status = os.system(wget)
if status == 2048: # 320kbps-mp3 is not available, so getting 128kbps-mp3.
wget = template_wgets % (sname, (durl[:-3] + '128') % songid)
status = os.system(wget)
if status not in [0, 2048]: # other http-errors, such as 302.
print '\n\n ----### ERROR ==> %d ###--- \n\n' % status
break
if __name__ == '__main__':
argv = sys.argv
if argv[1] == '-s' and argv[2]:
down_song(argv[2:])
elif argv[1] == '-a' and argv[2]:
down_album(argv[2])
else:
print 'Usage:\n -s songid1 songid2 songidn download some songs.\n -a albumid download an album.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment