python爬取酷狗音乐

 1 #encoding=utf-8
 2 """
 3 @File    :  kugou.py
 4 @Author  :  heram
 5 @Time    :  2019-07-15 16:25:47
 6 """
 7 
 8 import re
 9 import json
10 import time
11 import requests
12 import os
13 
14 def search(song_name):
15     """搜索歌曲"""
16     search_url = "https://songsearch.kugou.com/song_search_v2?callback=jQuery112405132987859127838_{}&page" \
17                  "=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_fil" \
18                  "ter=0&_={}&keyword={}".format(str(int(time.time()*1000)), str(int(time.time()*1000)), song_name)
19     obj = requests.get(search_url)
20     start = re.search("jQuery\d+_\d+\(?", obj.text)
21     data = json.loads(obj.text.strip().lstrip(start.group()).rstrip(")"))
22     return data['data']['lists']
23 
24 def download(song_list, dir):
25     """下载歌曲"""
26     # 展示前十个搜索结果
27     for i in range(10):
28         print(str(i + 1) + " >>> " + str(song_list[i]['FileName']).replace('', '').replace('', ''))
29     num = int(input("\n请输入您想要下载的歌曲序号:"))
30     print("请稍等,下载歌曲中...")
31     time.sleep(1)
32     file_hash = song_list[num - 1]['FileHash']
33     url = "http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash={}".format(file_hash)
34     obj = requests.get(url)
35     data = obj.json()  # json格式
36     download_url = data['url']
37     file_path = ''
38     try:
39         if download_url:
40             file_name = str(song_list[num - 1]['FileName']).replace('', '').replace('', '')
41             file_path = os.path.join(dir, ' - '.join(file_name.split(' - ')[::-1]) + ".mp3")
42             with open(file_path, "wb")as fp:
43                 fp.write(requests.get(download_url).content)
44             print("歌曲已下载完成!")
45         else:
46             print("无此歌曲链接")
47     except Exception as e:
48         if os.path.exists(file_path):
49             os.remove(file_path)
50         print(e)
51 
52 if __name__ == '__main__':
53     # 下载歌曲存放目录
54     dir = "music"
55     while True:
56         try:
57             # 搜索歌曲
58             song_list = search(input("请输入您想要搜索的歌曲名称:"))
59             # 下载歌曲
60             download(song_list, dir)
61         except Exception as e:
62             print(e)
63             pass

 

转载于:https://www.cnblogs.com/heram/p/11203226.html

你可能感兴趣的:(python爬取酷狗音乐)