利用python广西快乐十分源码出租爬取网易云歌手top50歌曲歌词

python广西快乐十分源码出租 dsluntan.com Q:3393756370 VX:17061863513近年来,发展迅速,成为了最炙手可热的语言。

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

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

在这里需要注意的是http://music.163.com/#/artist?id=1007170并不是真的我们需要的连接,真实的链接应该是http://music.163.com/artist?id=1007170

  1. 搞清楚了连接的问题之后,就要进行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

  1. 获取歌曲歌词

其实上一步中,我们已经可以得到每首歌对应的跳转链接,但是要是直接爬取那个链接的话会比较麻烦,尤其是token值的配置很复杂。为了简单起见,在这里运用的是网易云歌曲歌词API,此处可以参考链接http://moonlib.com/606.html

详细代码如下:

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
  1. 将获得歌词字符串写入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)

猜你喜欢

转载自blog.51cto.com/13916230/2156900