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('<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.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('<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://www.cnblogs.com/heram/p/11203226.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值