Python下载网易云歌单歌曲的示例代码

今天写了个下载脚本,记录一下

效果:

Python下载网易云歌单歌曲的示例代码

直接上代码:

# 网易云 根据歌单链接下载MP3歌曲
import requests
from bs4 import BeautifulSoup

def main():
  url = "https://music.163.com/#/playlist?id=3136952023" # 歌单地址 请自行更换
  if '/#/' in url:
    url = url.replace('/#/', '/')
  headers = {
    'Referer': 'http://music.163.com/',
    'Host': 'music.163.com',
    'cookie': '自己去网站拿,获取方式在下边',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  }

  s = requests.session()
  try:
    response = s.get(url, headers=headers).content
    soup = BeautifulSoup(response, 'lxml')
    lis = list(soup.find('ul'))
    fatherlis = ['歌单名:' + str(soup.find('h2').string)]
    for i in lis:
      sonlis = []
      sonlis.append(str(len(fatherlis)) + '.')
      sonlis.append(i.a.string)
      sonlis.append(str(i.a.get('href'))[str(i.a.get('href')).find('=') + 1:-1] + str(i.a.get('href'))[-1])
      fatherlis.append(sonlis)
  except:
    print("\n\t歌曲链接输入错误")
    exit('ERROR!')
  format = '{0:<10}\t{1:{3}<10}\t{2:<10}'
  print("从'{}'中找到了{}条歌曲".format(str(soup.find('h2').string), len(fatherlis) - 1))
  print('-------------------------------------------------------------------------------------------------')
  print('序号     歌曲名称    歌曲链接')
  for i in fatherlis:
    if fatherlis.index(i) == 0:
      continue
    else:
      print(
        format.format(i[0], i[1], 'http://music.163.com/song/media/outer/url?id=' + i[2] + '.mp3', chr(12288)))
      download_music(i[2],i[1])
  print('##########################下载完成##########################')

# 歌曲下载
def download_music(song_id,song_name):
  file = "./music/" # 保存音乐的文件路径
  wurl = "https://link.hhtjim.com/163/" # 外链地址
  song_url = wurl + song_id + ".mp3"
  # 获取歌曲16进制编码
  song = requests.get(song_url).content
  # 获取歌曲名称
  # 保存文件
  with open(file + song_name + '.mp3', 'wb') as f:
    f.write(song)
if __name__ == '__main__':
  main()

cookie获取方式

登录网易云web版 https://music.163.com/

Python下载网易云歌单歌曲的示例代码

复制粘贴到上方代码中,开始下载就好了

相关推荐