编辑代码

# coding:utf-8
#JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
import json
import math
import os
from pathlib import Path
from random import random
import requests


def searchSong(key,page):
    response = requests.get('https://apimusic.postudy.cn/search?offset='+str(page)+'&limit=30&keywords=' + key)
    song = {}
    if response.status_code == 200:
        data = json.loads(response.text)
        song = data['result']['songs']
    return song


def downmusic(name, isSong=True, size=30):
    turns = math.ceil(size/30)
    for i in range(turns):
        songs = searchSong(name,i)
        if isSong:
            songs = songs[0:1]
        for song in songs:
            if 'id' in song:
                print(song)
                response = requests.get('https://music.163.com/song/media/outer/url?id=' + str(song['id']) + '.mp3')
                path = './subdownload/'
                if not isSong:
                    path = './' + name + '/'
                    filePath = Path(path)
                    if not filePath.exists():
                        os.makedirs(path)
                with open(path + song['name'] + '.mp3', 'wb') as f:
                    if response.status_code == 200:
                        for j in response.iter_content(chunk_size=1024):
                            f.write(j)


def getSongNameList():
    with open('./songs.text', 'r', encoding='utf-8') as file:
        res = []
        for current_line in file:
            res.append(current_line.replace('\n', ''))
        print(res)
        print(len(res))


# getSongNameList()

downmusic('Taylor Swift', False, 31)