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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM