1 #!/usr/bin/env python
2 # _*_ coding:utf-8 _*_
3 import requests
4 import re
5 data = {
6 \'key\':\'朋友\'#搜索的歌曲关键词
7 }
8 #百度音乐搜索url
9 search_url = \'http://music.baidu.com/search\'
10 #发送http请求
11 search_response= requests.get(search_url, params=data)
12 #设置显示编码格式<head><meta encoding=""/>
13 search_response.encoding = \'utf-8\'
14 search_response_html = search_response.text
15 #获取歌曲id保存为字典格式,正则表达式
16 song_ids = re.findall(r\'"sid":(\d+),\',search_response_html)
17 #print(song_ids)
18 song_api = \'http://play.baidu.com/data/music/songlink\'
19 data = {#传参数用字典
20 \'songIds\':\',\'.join(song_ids),#把列表里面的元素用逗号拼接起来
21 \'hq\':0,
22 \'type\':\'mp3\',
23 \'pt\':0,
24 \'flag\':1,
25 \'s2p\':650,
26 \'prerate\':128,
27 \'bwt\':266,
28 \'dur\':231000,
29 \'bat\':266,
30 \'bp\':100,
31 \'pos\':65833,
32 \'auto\':0
33 }
34 #根据sid获取下载地址
35 song_response = requests.post(song_api,data=data)
36 print(song_response)
37 song_info = song_response.json()#将返回的歌曲转成字典
38 print(song_info)
39 song_info = song_info[\'data\'][\'songList\']
40 print(song_info)
41 for song in song_info:#遍历下载
42 song_name = song[\'songName\']
43 with open(\'d:/T/%s.mp3\' % song_name, \'wb\') as f:
44 print(song[\'songLink\'])
45 response = requests.get(song[\'songLink\'])
46 f.write(response.content)
47 #print(song_ids)