python爬取酷狗音乐

编程入门 行业动态 更新时间:2024-10-28 12:26:25
 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/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('<em>', '').replace('</em>', ''))
29     num = int(input("\n请输入您想要下载的歌曲序号:"))
30     print("请稍等,下载歌曲中...")
31     time.sleep(1)
32     file_hash = song_list[num - 1]['FileHash']
33     url = "http://m.kugou/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('<em>', '').replace('</em>', '')
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://wwwblogs/heram/p/11203226.html

更多推荐

python爬取酷狗音乐

本文发布于:2023-06-14 04:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1440088.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:酷狗   音乐   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!