Teach you to use Python to download music in batches. You don't need to install a player, download it directly!

Posted by deth4uall on Fri, 17 Dec 2021 15:56:25 +0100

The songs we want to listen to are only available in specific music software, but we don't think it's too troublesome to download the software. It's easy to say that Python can implement it casually!

We take Qiuqiu music as an example to do a function of searching and downloading music.

Before we start, we recommend a place for communication. You can communicate here if you have any questions~
Many children can't stick to their study because they don't have good learning materials or can't solve problems efficiently. Therefore, I have prepared a lot of learning materials here for everyone I'll get it for free Including today's code and video tutorials. If you don't understand the article, you can also watch the video.

The software used is Anaconda 5 2.0 (Python 3.6.5) and pycharm. Anaconda comes with Python. You don't need to install Python if anaconda is installed.

Then you need to install a requests library. Press and hold win+r on the keyboard, enter cmd in the pop-up search box, press enter, and enter pip install requests in the newly pop-up command prompt window to complete the installation.

A little wordy, but a little friendly to zero basis.

Knowledge points:

requests
json
pprint

OK, let's try

First arrange the modules to be used and import them.

import requests
import json
import os

Since we want to climb a website, if there is anti pickpocketing, we must solve this problem. For example, today, we can use the headers module to simulate a browser to visit the website.

So where can I find headers?

Click on the browser page: right click – > check – > (or directly press F12), and the rest will follow the operation shown in the figure. You need to press Fn+F5 to refresh the web page

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
}

Then, since we want to search and download, we have to do the search function first.

def get_music_info():
    """Search function"""
    music_info_list = []
    name = input('Please enter a singer or song:')  # 
    page = input('Please enter page number:')
    num = input('Please enter the number of data to be returned for the current page number:')
    url = f'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p={page}&n={num}&w={name}'
    response = requests.get(url, headers=headers).text  # Got a string
    # Cut the response into json. The format is similar to a dictionary, but it is still a string
    music_json = response[9:-1]
    # json to dictionary
    music_data = json.loads(music_json)  # Convert to dictionary
    # print(music_data)
    music_list = music_data['data']['song']['list']
    for music in music_list:
        music_name = music['songname']  # The name of the song
        singer_name = music['singer'][0]['name']  # Singer's name
        songmid = music['songmid']
        music_info_list.append((music_name, singer_name, songmid))
    return music_info_list

Look at the effect
Get encrypted vkey

def get_purl(music_info_list):
    """Single song address splicing"""
    music_data = []
    for music in music_info_list:
        music_name = music[0]
        singer_name = music[1]
        songmid = music[2]
        url = 'https://u.y.qq.com/cgi-bin/musicu.fcg?data={"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"8846039534","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"8846039534","songmid":["%s"],"songtype":[0],"uin":"1152921504784213523","loginflag":1,"platform":"20"}},"comm":{"uin":"1152921504784213523","format":"json","ct":24,"cv":0}}' % songmid
        response = requests.get(url, headers=headers).json()  
        purl = response['req_0']['data']['midurlinfo'][0]['purl']
        full_media_url = 'http://dl.stream.qqmusic.qq.com/' + purl
        music_data.append(
            {
                'music_name': music_name,
                'singer_name': singer_name,
                'full_media_url': full_media_url
            })
    return music_data

If the data you get is {} json() he will directly help us convert it into a dictionary.

Then download

if determines whether there is a song download folder. if not, a song download folder will be automatically created. Of course, the name can be changed by yourself.

def save_music_mp3(music_data):
    """Download songs"""
    if not os.path.exists('Song download'):  
        os.mkdir('Song download')  
    for music in music_data:
        music_name = music['music_name']
        singer_name = music['singer_name']
        full_url = music['full_media_url']
        music_response = requests.get(full_url, headers=headers).content
        with open('Song download/%s-%s.mp3' % (music_name, singer_name), 'wb')as fp:
            fp.write(music_response)
            print('[%s]Saved successfully!' % music_name)


if __name__ == '__main__':
    music_info_list = get_music_info()
    music_data = get_purl(music_info_list)
    save_music_mp3(music_data)

Now let's see the effect
Page number and number of data can not be entered. He will download the first page by default, and one page is ten songs.
You can also download other pages
Then I just want one
This is the song just obtained automatically
Of course, only the code is boring. We can also package the code into an exe program and run it directly~

I won't repeat how to do it one by one. The method is simple. Baidu can do it in minutes. Let me show you the effect.
Although there is only one command box page, Shan is at least an exe file that can run without installing Python. No, if you want the page to look good, you have to make another interface to complete it next time~

Topics: Python Programming Programmer crawler computer