Retrieving and Downloading KuGou Music by Analyzing API Requests
This article explains how to extract song information from KuGou by inspecting network requests, simplifying URLs, generating required MD5 signatures, constructing authenticated API calls, and using Python to download the resulting audio files to a local directory.
The goal is to input a song name or artist, list the corresponding music information, and download the selected track to a specified local folder.
1. Request Analysis By playing a song in Chrome and opening the developer tools, the article identifies the GET request URL that returns the song data, noting that many parameters are unnecessary and that a valid request also requires specific cookies.
2. Parameter Extraction The search request URL is examined, revealing parameters such as keyword , page , pagesize , and dynamic values like signature , clienttime , mid , and uuid . The signature is generated by MD5‑encrypting a concatenated string of fixed and timestamp‑based parameters using Python's hashlib module.
Sample Python code for generating the signature and constructing the final URL:
<code>def MD5Encrypt(self, text):
k = time.time()
k = int(round(k * 1000))
info = ["NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt", "bitrate=0", "callback=callback123",
"clienttime={}".format(k), "clientver=2000", "dfid=-", "inputtype=0",
"iscorrection=1", "isfuzzy=0", "keyword={}".format(text), "mid={}".format(k),
"page=1", "pagesize=30", "platform=WebFilter", "privilege_filter=0",
"srcappid=2919", "tag=em", "userid=-1", "uuid={}".format(k), "NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt"]
new_md5 = md5()
info = ''.join(info)
new_md5.update(info.encode(encoding='utf-8'))
signature = new_md5.hexdigest()
url = ('https://complexsearch.kugou.com/v2/search/song?callback=callback123&keyword={0}'
'&page=1&pagesize=30&bitrate=0&isfuzzy=0&tag=em&inputtype=0&platform=WebFilter&userid=-1'
'&clientver=2000&iscorrection=1&privilege_filter=0&srcappid=2919&clienttime={1}&'
'mid={2}&uuid={3}&dfid=-&signature={4}').format(text, k, k, k, signature.upper())
return url</code>After obtaining the search results, the script parses the JSON to extract fields such as SongName , SingerName , FileHash , and other quality‑specific hashes. It then builds the final download URL (e.g., https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash={FileHash} ) and saves the MP3 file.
Sample code for downloading and saving the audio file:
<code># -*- coding: utf-8 -*-
import time, json, requests, os, re
from hashlib import md5
class KuGouMusic(object):
def __init__(self):
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
# ... (MD5Encrypt method as above) ...
def get_html(self, url):
cookie = 'kg_mid=...; kg_dfid=...'.split('; ')
cookie_dict = {c.split('=')[0]: c.split('=')[1] for c in cookie}
response = requests.get(url, headers=self.headers, cookies=cookie_dict)
response.raise_for_status()
response.encoding = 'utf-8'
return response.text
def parse_text(self, text):
# parse JSON and print a table of results
...
def save_file(self, song_text):
data = json.loads(song_text)
audio_name = data['audio_name']
play_url = data['play_url']
resp = requests.get(play_url, headers=self.headers)
with open(os.path.join('./download', audio_name + '.mp3'), 'wb') as f:
f.write(resp.content)
print('下载完毕!')
if __name__ == '__main__':
kg = KuGouMusic()
search_info = input('请输入歌名或歌手: ')
search_url = kg.MD5Encrypt(search_info)
search_text = kg.get_html(search_url)
hash_list = kg.parse_text(search_text[12:-2])
while True:
idx = int(input('请输入要下载歌曲的序号(-1退出): '))
if idx == -1:
break
song_url = f'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash={hash_list[idx][0]}'
song_text = kg.get_html(song_url)
kg.save_file(song_text)</code>The final section notes that the KuGou API is relatively simple compared to other services, and the author expresses enthusiasm for the platform's extensive music library.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.