1. 程式人生 > >利用python廣西快樂十分源碼出租爬取網易雲歌手top50歌曲歌詞

利用python廣西快樂十分源碼出租爬取網易雲歌手top50歌曲歌詞

代碼提示 安裝 json 如果 https enc utf _id ebp

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)

利用python廣西快樂十分源碼出租爬取網易雲歌手top50歌曲歌詞