百度音乐接口下载歌曲

#!/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'
找了好久才找到的,学习一下
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值