利用python爬取网易云歌手top50歌曲歌词

python近年来,发展迅速,成为了最炙手可热的语言。

那么如何来进行网易云歌手top50的歌曲歌词爬取呢

1. 首先进行网易云并进行喜欢的歌手搜索如下:

在这里需要注意的是并不是真的我们需要的连接,真实的链接应该是

2. 搞清楚了连接的问题之后,就要进行BeautifulSoup对网易进行抓取

核心代码如下:

#encoding=utf-8
import requests
import json
import re
import os
from bs4 import BeautifulSoup

headers = {
	Referer:https://music.163.com,
	Host: music.163.com,
	User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36,
	Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
}

def get_top50(artist_id):
	url = "http://music.163.com/artist?id="+str(artist_id)

	s = requests.session()
	s = BeautifulSoup(s.get(url,headers=headers).content,"lxml")

	artist_name = s.title

	main = s.find(ul,{class:f-hide})
	main = main.find_all(a)

	song = {}
	song[artist_name] = artist_name.text
	song[list] = main

	return song
# 返回的song是一个dict,有两个键值对,artist_name记录歌手名称,list记录歌曲名称以及href值
# 要想获得top50歌曲的id以及链接需要对返回值进行如下处理
# song[href]  --- 歌曲链接
# song.text     --- 歌曲名称

如果使用上述代码提示出错,那可能是没有安装BeautifulSoup和lxml的包。这个时候需要首先进入Python的安装路径,然后找到script文件夹,打开cmd进入script所在目录,使用命令

pip install BeautifulSoup
pip install lxml

#这里需要注意的是pip的版本要与使用的python版本一致
#譬如本机的python使用的是3.0版本以上,就需要使用pip3

3. 获取歌曲歌词

详细代码如下:

def get_lyric(song_id):
	list = song_id.split(=)
	id = list[1]
	url = "http://music.163.com/api/song/lyric?id="+str(id)+"&lv=1&kv=1&tv=-1"

	s = requests.session()
	s = BeautifulSoup(s.get(url,headers=headers).content,"lxml")
	json_obj = json.loads(s.text)

	final_lyric = ""
	if( "lrc" in json_obj):
		inital_lyric = json_obj[lrc][lyric]
		regex = re.compile(r[.*])
		final_lyric = re.sub(regex,,inital_lyric).strip()

	return final_lyric

4. 将获得歌词字符串写入txt文件

def ConvertStrToFile(dir_name,filename,str):
	if (str == ""):
		return
	filename = filename.replace(/,)
	with open(dir_name+"//"+filename+".txt",w) as f:
		f.write(str)

该项目详细代码见本人的GitHub:

经验分享 程序员 微信小程序 职场和发展