1. 程式人生 > >Python爬去百度音樂

Python爬去百度音樂

百度音樂

編譯器環境:Python3.6


代碼:

#!/usr/bin/env python
#-*-coding=utf-8 -*-
#AUTHOR:duwentao

import  requests
import re
import json

def get_sids_by_name(name):
    url = 'http://music.baidu.com/search'
    data = {
        'key':name
    }
    reponse = requests.get(url,params=data)
    reponse.encoding='utf-8'
    html = reponse.text
    #print (html)
    ul = re.findall(r'<ul.*</ul>', html, re.S)[0]
    #print(ul)
    # 獲取sid sid&quot;:551560464
    sids = re.findall(r'sid&quot;:(\d+),', ul, re.S)
    return sids


def get_mp3_by_id(song_id):
    song_id = song_id

    api ='http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&format=jsonp&callback=jQuery17205500581185420972_1513324047403&songid=%s&_=1513324048127' % song_id

    response = requests.get(api)
    data = response.text

    data = re.findall(r'\((.*)\)', data)[0]
    data = json.loads(data)
    title = data['songinfo']['title']
    mp3_url = data['bitrate']['show_link']
    mp3_data = requests.get(mp3_url).content

    with open('%s.mp3' % title,'wb') as f:
        f.write(mp3_data)
        print ("下載完成")
        f.close()
sid = input("請輸入歌手的名字:")
sids = get_sids_by_name(sid)

for si in sids:
    print ("正在下載sid為",si)
    get_mp3_by_id(si)



執行結果:

技術分享圖片

技術分享圖片


微信公眾號:

技術分享圖片

Python爬去百度音樂