python 网易云歌词获取
·
自己车子的播放器是要联网下载歌词,发现还是有很多老歌的歌词不能正常下载到,于是自己动手弄个歌词的下载脚本,同时也当是练练手,好久没码代码了。
1.首先 两个 从网易云 取歌曲信息的API地址(网上查找得到的,目前能用):
自动搜索歌曲数据,可以获得 歌曲ID
https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s={歌曲信息}&type=1&offset=0&total=true&limit=10
通过ID,获取歌词
https://music.163.com/api/song/lyric?os=pc&id={歌曲ID}&lv=-1
2.Python 脚本如下:(仅供参考,作为学习交流用)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Project: test
# File : test.py
# Author : Long.Xu <fangkailove@yeah.net>
# http://gnolux.blog.csdn.net
# QQ:26564303 weixin:wxgnolux
# Time : 2024/12/15 18:58
# Copyright 2024 Long.Xu All rights Reserved.
import base64
import json
import os
import random
import time
import urllib.parse
from urllib import request
# 通过网易云songID去取歌词
def get_song_lyric_by_id(songid):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.%s" % random.uniform(1,40)}
lyric_url = "https://music.163.com/api/song/lyric?os=pc&id=%s&lv=-1" % songid
req = request.Request(url=lyric_url, headers=headers)
r = request.urlopen(req)
c = r.read()
j = json.loads(c)
if j.get('lrc'):
return j['lrc']['lyric']
# 通过歌名歌手信息查找网易云里的歌曲编号
def get_songid_by_name(songname):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"}
song_url = "https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%s&type=1&offset=0&total=true&limit=10" % urllib.parse.quote(songname)
req = request.Request(url=song_url, headers=headers)
r = request.urlopen(req)
c = r.read()
j = json.loads(c)
if j.get("result"):
return j["result"]["songs"][0]["id"]
else:
print(songname,j)
# 找到目录下所有 .mp3,.flac文件,并按文件名为网易云下载歌词保存在同目录。
def downloadlyric(file_dir):
file_dir = os.path.expanduser(file_dir)
for root, dirs, files in os.walk(file_dir):
print("*"*80)
for file in files:
file_path = root + '/' + file
basename = os.path.basename(file_path)
dirname = os.path.dirname(file_path)
mainname, extname = os.path.splitext(basename)
if extname in ['.mp3', '.flac']:
outpath = dirname + '/' + mainname + '.lrc'
if not os.path.exists(outpath):
songid = get_songid_by_name(mainname)
if songid:
lyricstr = get_song_lyric_by_id(songid)
if lyricstr:
if len(lyricstr.split('\n')) > 8:
with open(outpath,'w') as f:
f.write(lyricstr)
else:
print(basename,"没有对应的歌词")
else:
print(basename,"没有对应的歌词")
else:
print(basename,"找不到此歌曲")
if __name__ == '__main__':
downloadlyric("~/Music/居家古风")
更多推荐
所有评论(0)