Preface:

A brand new week, of course, is to master a new “terminal technology” to start, without any more nonsense, let’s begin happily ~

The development tools

Python version: 3.6.4

Related modules:

The argparse module;

Pick module;

Click the module;

DecryptLogin module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required modules.

Introduction of the principle

Since you want to see the daily song recommendation of netease Cloud in the terminal, the first natural thing is to simulate login to netease Cloud. This part can be realized by using the DecryptLogin package opened before the public account:

Mock login
@staticmethod
def login(username, password) :
    lg = login.Login()
    infos_return, session = lg.music163(username, password)
    return session
Copy the code

Next, let’s take a look at how to get a daily song recommendation from netease Cloud. Simple packet capture analysis, you can find the following link:

Request it to return daily song recommendations:

Ok, now let’s go back to the previous method and make a break point to see what parameters need to be submitted to get the daily recommended song information:

Netease cloud personal music charts to climb

Here are the results:

data = {
        'crsf_token': csrf,
        'limit': '999'.'offset': '0'.'total': 'true'
    }
Copy the code

A quick test:

Get daily recommendations
def getdailyrecommend(self) :
    url = 'http://music.163.com/weapi/v2/discovery/recommend/songs?csrf_token='
    data = {
            'crsf_token': self.csrf,
            'limit': '999'.'offset': '0'.'total': 'true'
        }
    data = self.cracker.get(data)
    response = self.session.post(url, headers=self.headers, data=data)
    response_json = response.json()
    print(response_json)
Copy the code

The effect is as follows:

Next, we extract the data we need from the returned data:

response_json = response.json()
daily_recommend_infos = {}
if response_json['code'] = =200:
    for item in response_json['recommend']:
        songname = item['name']
        songid = item['id']
        singer = item['artists'] [0] ['name']
        h = item['hMusic'].get('bitrate'.320000) if item['hMusic'] else 320000
        m = item['mMusic'].get('bitrate'.192000) if item['mMusic'] else 192000
        l = item['lMusic'].get('bitrate'.128000) if item['lMusic'] else 128000
        brs = [h, m, l]
        daily_recommend_infos[songid] = ['%s By %s' % (songname, singer), brs]
    return daily_recommend_info
else:
    raise RuntimeError('Failed to get song of the Day recommendations, please check your network and run the program again... ')
Copy the code

Finally, as in the previous article:

To write a netease cloud personal playlist downloader?

Add a song download feature for the pleasure of viewing daily song recommendations and downloading your favorite songs to listen to:

Download a song
def downloadSong(self, songid, songname, brs, savepath='. ') :
    play_url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
    print('Downloading -- > %s' % songname)
    for br in brs:
        data = {
                    'ids': [songid],
                    'br': br,
                    'csrf_token': self.csrf
                }
        res = self.session.post(play_url+self.csrf, headers=self.headers, data=self.cracker.get(data))
        if res.json()['code'] = =200:
            download_url = res.json()['data'] [0].get('url'.' ')
            if download_url:
                break
    with closing(self.session.get(download_url, headers=self.headers, stream=True, verify=False)) as res:
        total_size = int(res.headers['content-length'])
        if res.status_code == 200:
            label = '[FileSize] : % 0.2 f MB' % (total_size/(1024*1024))
            with click.progressbar(length=total_size, label=label) as progressbar:
                with open(os.path.join(savepath, songname+'. '+download_url.split('. ')[-1]), "wb") as f:
                    for chunk in res.iter_content(chunk_size=1024) :if chunk:
                            f.write(chunk)
                            progressbar.update(1024)
Copy the code

That’s the end of this article. Thank you for watching my daily series of Python emulation logins. In my next article, I’ll be sharing Python’s geolocation information for obtaining IP addresses.

To thank the readers, I’d like to share some of my recent programming gems to give back to each and every one of you.

Dry goods are mainly:

① More than 2000 Python ebooks (both mainstream and classic)

Python Standard Library (Chinese version)

(3) project source code (forty or fifty interesting and classic practice projects and source code)

④Python basic introduction, crawler, Web development, big data analysis videos (suitable for small white learning)

⑤ Python Learning Roadmap

All done~ complete source code + dry plus Python novice learning exchange community: 594356095