use Python Make music aggregator downloaders

writing | So and so white rice

source :Python technology 「ID: pythonall」

 use Python Make music aggregator downloaders

Music now APP There's a lot of , In order not to download a lot of APP, So let's use it python Made an aggregate music downloader , Now we have Migu music 、QQ music , Here is the effect

 use Python Make music aggregator downloaders

install

You need to install an auxiliary module prettytable, Table output for beautifying the console

pip install prettytable

Extract music links

Search for music

To download QQ Music as an example , On the home page (https://y.qq.com/) Search in the search box on << cheeky >>, open F12 The console panel , You can find the search link as shown in the figure below , This link returns a list of music json strand

 use Python Make music aggregator downloaders

def get_request(self, url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
}
response = requests.get(url, headers = headers)
if response.status_code == 200:
return response
except Exception as e:
print(" Request error :", e)
return None
def search_music(self, key):
# 20: Inquire about 20 Data ,key: keyword
url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=1&n=%d&w=%s' % (20, key)
resp = self.get_request(url)
resp_json = json.loads(resp.text[9:][:-1])
data_song_list = resp_json['data']['song']['list']
song_list = []
for song in data_song_list:
singers = [s.get("name", "") for s in song.get("singer", "")]
song_list.append({'name': song['songname'], 'songmid': song['songmid'], 'singer': '|'.join(singers)})
return song_list

Sample results :

[{'name': ' At the foot of Mount Fuji ', 'songmid': '003dtkNk26WhJD', 'singer': ' Eason Chan '}, {'name': ' Don't talk ', 'songmid': '002B2EAA3brD5b', 'singer': ' Eason Chan '}, ...., {'name': ' The best loser ', 'songmid': '003hFxQh276Cv5', 'singer': ' Eason Chan '}]

Get download link

Click the songs in the music list page to the music playing page , Find more than one in the control panel to m4a Music at the end of the actual link

 use Python Make music aggregator downloaders

Its parameter part has a vkey Parameters of , hold vkey As a keyword in Network Search for , Find one musics.fcg The link at the end ,vkey That's what it returns json In a string , additional purl The value of is the one above m4a link , The final will be https://ws.stream.qqmusic.qq.com and purl Put together music links ,musics.fcg In the link guid The parameter is a random number ,songmid The parameters are for the single music above songmid,uin Parameter is QQ Number

 use Python Make music aggregator downloaders

def download_url(self, song):
guid = str(random.randrange(1000000000, 10000000000))
purl_url = 'https://u.y.qq.com/cgi-bin/musicu.fcg?' \
'&data={"req":{"param":{"guid":" %s"}},' \
'"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"%s","songmid":["%s"],"uin":"%s"}},"comm":{"uin":%s}}' \
% (guid, guid, song['songmid'], 0, 0)
resp = self.get_request(purl_url)
if resp is None:
return 'N', 'None', '.m4a'
resp_json = json.loads(resp.text)
purl = resp_json['req_0']['data']['midurlinfo'][0]['purl']
# Some music can't be heard on the website
if len(purl) < 1:
msg = 'N'
download_url = 'http://ws.stream.qqmusic.qq.com/' + purl
song_data = self.get_request(download_url)
if song_data:
msg = 'Y'
return msg, download_url, '.m4a'

Sample results :

 use Python Make music aggregator downloaders

The download link with only one domain address means that the music can only be heard on the client , The web version doesn't listen

It's over here QQ Music search 、 Grab script , Grab Migu music in the same way (http://m.music.migu.cn) Make Migu music script , Migu music is easier to crawl

Command line main interface

The main function of the main interface is to display the searched music in the form of table and download music in the form of serial number

import os
from qqMusic import QQMusic
from miguMusic import MiGuMusic
from prettytable import PrettyTable
class MusicBox(object):
def __init__(self):
pass
def download(self, data, songName, type):
save_path = 'music/' + songName + '.' + type
file = 'music'
if os.path.exists(file):
pass
else:
os.mkdir('music')
try:
print("{} In the download .....".format(songName), end='')
with open(save_path, 'wb') as f:
f.write(data)
print(" Download complete ")
except Exception as err:
print(" File write error :", err)
return None
def main(self):
print(' Please enter the song or singer you want to download :')
key = input()
print(' Searching for ..\033[32mQQ music \033[0m', end='')
qqMusic = QQMusic()
qq_song_list = qqMusic.main(key)
print('...\033[31m Migu music \033[0m')
miguMusic = MiGuMusic()
migu_song_list = miguMusic.main(key)
qq_song_list.extend(migu_song_list)
song_dict = {}
for song in qq_song_list:
key = song['name'] + '\\' + song['singer']
s = song_dict.get(key)
if s:
if s['msg'] != 'Y':
song_dict[key] = song
else:
song_dict[key] = song
i = 0
table = PrettyTable([' Serial number ', ' singer ', ' download ', ' Da da da '])
table.border = 0
table.align = 'l'
for song in list(song_dict.values()):
i = i + 1
table.add_row([str(i), song['singer'], song['msg'], song['name']])
print(table)
while 1:
print('\n Please enter the information you want to download , Press q sign out :')
index = input()
if index == 'q':
return
song = list(song_dict.values())[int(index) - 1]
data = qqMusic.get_request(song['downloadUrl'])
if song['msg'] == 'Y':
self.download(data.content, song['name'], song['type'])
else:
print(' The song is not allowed to download ')
if __name__ == '__main__':
musicBox = MusicBox()
musicBox.main()

summary

The most important part of the music aggregation Downloader is that the crawler grabs the data of each music website , The command-line approach eliminates the need to draw GUI The job of .