import time
import os
import requests
import json
from concurrent.futures import ThreadPoolExecutor

def getsongsid(id=3778678):
    root = "http://localhost:3000"
    cmd = f"/playlist/detail?id={id}"
    url = root + cmd
    res = requests.get(url)
    res_dict = json.loads(res.text)
    playlist = res_dict["playlist"]["trackIds"]
    ob = []
    for i in playlist:
        temp = {}
        temp["id"] = i["id"]
        ob.append(temp)
    return ob

# 第二步:循环遍历获取歌曲详细信息(ID ,歌名,歌手名字,下载链接)

def downsong(i):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}
    import requests,json
    root = "http://localhost:3000"
    cmd = f"/song/detail?ids={i['id']}"
    url = root + cmd
    res = requests.get(url,headers=headers)
    res_dict = json.loads(res.text)
    i["name"] = res_dict["songs"][0]["name"]
    i["author"] = res_dict["songs"][0]["ar"][0]["name"]
    i["url"] = f"http://music.163.com/song/media/outer/url?id={i['id']}.mp3"

    # 判断是否可以下载
    url = f"{root}/song/url?id={i['id']}"
    res = requests.get(url,headers=headers)
    res_dict = json.loads(res.text)
    if res_dict["data"][0]["url"] != None:
        # print("可以下载")
        url = f"http://music.163.com/song/media/outer/url?id={i['id']}.mp3"
        # print(url)
        # print(f"正在下载{i['name']}...")
        r = os.path.isfile(f"D://2/{i['name']}.mp3")
        if r == False:
            res = requests.get(url,headers=headers)
            with open(f"D://1/{i['name']}.mp3","wb") as f:
                f.write(res.content)
    else:
        print(f"{i['name']}不可以下载")

def main():
    ob = getsongsid(3778678)  # id = 587771511  # 我喜欢的音乐 # id = 5260377435  # 健身专属
    print(ob)
    tps = ThreadPoolExecutor(100)
    for i in ob:
        tps.submit(downsong,i)
        time.sleep(0)
    tps.shutdown()
if __name__ == "__main__":
    main()
View Code
02-14 04:46