示例代码如下:
import requests
import multiprocessing
import time
# 下载歌曲
def downloader(item):
resp = requests.get(item['song_link'])
with open('./song/' + item['name'] + '.m4a', 'wb') as fp:
print('正在下载', item['name'])
fp.write(resp.content)
def main():
urls = [
{
"name": "朋友",
"song_link": "https://m701.music.126.net/20210326141615/978689dfbb858c4da53e50df6474cb60/jdyyaac/5653/525e/055d/a9454d96a2e420643b002734d6f7fe08.m4a"
},
{
"name": "当年情",
"song_link": "https://m701.music.126.net/20210326141615/978689dfbb858c4da53e50df6474cb60/jdyyaac/5653/525e/055d/a9454d96a2e420643b002734d6f7fe08.m4a"
},
{
"name": "Monical",
"song_link": "https://m10.music.126.net/20210326141848/1e966464daff62a40571991f73219c7b/yyaac/obj/wonDkMOGw6XDiTHCmMOi/3082407828/2766/750d/e2ab/8daef342fd1e3b4ff25a36055bd58efd.m4a"
},
{
"name": "朋友别哭",
"song_link": "https://m801.music.126.net/20210326141938/ed9ab9235cd76d5184eaa561fe6de4b0/jdyyaac/525c/540f/0f5d/e684123968ce2568614a87e2c31a2814.m4a"
}
]
start_time = time.time()
# 开启6个进程
pool = multiprocessing.Pool(6)
for item in urls:
# downloader(item)
pool.apply_async(func=downloader, args=(item, ))
pool.close()
pool.join()
end_time = time.time()
print('下载总耗时', end_time - start_time)
if __name__ == '__main__':
main()