#!/usr/bin/python
# -*- coding:utf-8 -*-
from xml.etree import ElementTree as XmlTree
import os
import sys
import urllib
DOWNLOAD_URL = 'http://box.zhangmen.baidu.com/x?op=12&count=1&title=%s$$%s$$$$'
if len(sys.argv) < 2:
print 'Usage: ./download_music.py MusicName AuthorName'
sys.exit()
music_name = sys.argv[1]
try:
author_name = sys.argv[2]
except:
author_name = ""
link = DOWNLOAD_URL % (music_name, author_name)
read = urllib.urlopen(link) #返回一个文件类型的对象
xml = read.read()
read.close()
'''转换编码格式'''
xml = xml.decode('gb2312').encode('UTF-8')
xml = xml.replace('encoding="gb2312"', 'encoding="UTF-8"')
try:
root = XmlTree.fromstring(xml) #加载xml字符串
# If this line enabled, will download lower quality mp3
# url = root.find('url')
# If this line enabled, will download higher quality mp3
url = root.find('durl')
encd = url.find('encode')
decd = url.find('decode')
addr = encd.text
exts = decd.text
base = addr[:addr.rfind('/')]
full = os.path.join(base, exts) #拼接,取得歌曲真正的下载地址
print '>>>Start to download music named %s' % music_name
urllib.urlretrieve(full, music_name+'.mp3') #将歌曲下载到本地
print '>>>Download Completed'
except Exception,e:
print 'Exception:',e
print '>>>Music name is not matched with author name'
找了好久才找到的,学习一下
百度音乐接口下载歌曲
最新推荐文章于 2024-05-09 16:24:43 发布