python soup歌词_【python】 爬取网易云音乐 专辑图片+歌词
要求
下載一百首歌曲,相關圖片以及相關文字信息
存儲方式分別為:
.mp3
.txt
.png
比如第一首歌曲相關信息為001.mp3\001.txt\001.png
覺得像是小朋友的抄寫作業有沒有……
想試試看爬-雖然我也不知道行不行
思路
一開始的想法是全都直接根據歌單獲取歌曲的ID,然后每首歌都按那個格式001.mp3\001.txt\001.png存下來
后來發現我好像做不到直接下mp3……因為在網頁版一點會跳出來請在PC版下載(咦所以結果我也不知道怎么操作……)
然后計劃就變成了 - 爬圖片+歌詞,命名成和音樂同個格式,然后按名字排序之后就可以用改名軟件批量直接改成這個樣子了(自以為很機智)
雖然本人對python的理解還停留在曾經因作業要求爬過一次的莎士比亞全集……
準備
軟件
如果你和我一樣智障的話你可能需要如下資料
然后不一定都有用……因為我是一直在改別人的代碼……
exprcted an indented block - 調整縮進
具體操作
美湯(程序員都是吃貨系列
先對著一個歌單把ID爬下來
然后再對著ID爬各種……(只能想到這樣了)
具體實現
應該可以從如下代碼中看到以上一些參考文獻的痕跡(捂臉)
雖然拼湊痕跡有點明顯orz反正能大概實現功能已經很滿意了
讀取歌單
# 爬取某歌單的所有歌曲ID
def getSongIdList():
songIdList = []
playListUrl = 'http://music.163.com/playlist?id=918802417'#空城 finished
soup = BeautifulSoup(_session.get(playListUrl).content)
ul = soup.find('ul', attrs={'class': 'f-hide'})
for li in ul.findAll('li'):
songId = (li.find('a'))['href'].split('=')[1]
print songId
songIdList.append(songId)
# 去一下重復的歌曲I
songIdList = list(set(songIdList))
return songIdList
歌曲名+歌手名
url = BASE_URL + 'song?id=' + str(song.id)
url.decode('utf-8')
soup = BeautifulSoup(_session.get(url).content)
strArr = soup.title.string.split(' - ')
song.singer = strArr[1]
name = strArr[0].encode('utf-8')
歌詞
def get_lyric_by_music_id(music_id,songstr):#定義一個函數,通過音樂的id得到歌詞
lrc_url = 'http://music.163.com/api/song/lyric?' + 'id=' + str(music_id) + '&lv=1&kv=1&tv=-1'
#lrc_url = BASE_URL + 'song?id=' + str(music_id)
lyric=requests.get(lrc_url)
json_obj=lyric.text
#print(json_obj)
j=json.loads(json_obj)
file_atr = 'E:\\music\\' + songstr + '.txt'
f = open(file_atr,'wb')
f.writelines(songstr.encode('utf8'))
f.write('\n')
try:#部分歌曲沒有歌詞,這里引入一個異常
lrc=j['lrc']['lyric']
pat=re.compile(r'\[.*\]')
lrc=re.sub(pat,"",lrc)
lrc=lrc.strip()
#print type(lrc)
f.writelines(lrc.encode('utf8'))
f.close()
return lrc
except KeyError as e:
f.writelines('No Available Lyric on CloudMusic')
f.close()
專輯封面
def get_img(url,songstr): ##保存圖片
#print '##正在讀取圖片##'
#print url
urlStream=urllib.urlopen(url)
htmlString=urlStream.read()
#print htmlString
if( len(htmlString)!=0 ):
patternString=r'http://p1.music.126.net/.*?.jpg'
searchPattern=re.compile(patternString)
imgUrlList=searchPattern.findall(htmlString)
imgUrl =imgUrlList[0]
#print imgUrl
if( len(imgUrl)!= 0 ):
urllib.urlretrieve(imgUrl,'E:\\music\\' + songstr + '.jpg')
完整代碼
# encoding=utf8
import requests
from selenium import webdriver
from bs4 import BeautifulSoup
import os, json
import base64
import warnings
import re,urllib,uuid
warnings.filterwarnings("ignore")
BASE_URL = 'http://music.163.com/'
_session = requests.session()
localPath='d://pythonPath'
def createFileWithFileName(localPathParam,fileName):
totalPath=localPathParam+'//'+fileName
if not os.path.exists(totalPath):
file=open(totalPath,'a+')
file.close()
class Song(object):
def __lt__(self, other):
return self.commentCount > other.commentCount
# 爬取某歌單的所有歌曲ID
def getSongIdList():
songIdList = []
playListUrl = 'http://music.163.com/playlist?id=918802417'#空城 finished
soup = BeautifulSoup(_session.get(playListUrl).content)
ul = soup.find('ul', attrs={'class': 'f-hide'})
for li in ul.findAll('li'):
songId = (li.find('a'))['href'].split('=')[1]
print songId
songIdList.append(songId)
# 去一下重復的歌曲I
songIdList = list(set(songIdList))
return songIdList
# 獲取歌曲信息
def matchSong(songId):
song = Song()
song.id = songId
return song
def get_lyric_by_music_id(music_id,songstr):#定義一個函數,通過音樂的id得到歌詞
lrc_url = 'http://music.163.com/api/song/lyric?' + 'id=' + str(music_id) + '&lv=1&kv=1&tv=-1'
#lrc_url = BASE_URL + 'song?id=' + str(music_id)
lyric=requests.get(lrc_url)
json_obj=lyric.text
#print(json_obj)
j=json.loads(json_obj)
file_atr = 'E:\\music\\' + songstr + '.txt'
f = open(file_atr,'wb')
f.writelines(songstr.encode('utf8'))
f.write('\n')
try:#部分歌曲沒有歌詞,這里引入一個異常
lrc=j['lrc']['lyric']
pat=re.compile(r'\[.*\]')
lrc=re.sub(pat,"",lrc)
lrc=lrc.strip()
#print type(lrc)
f.writelines(lrc.encode('utf8'))
f.close()
return lrc
except KeyError as e:
f.writelines('No Available Lyric on CloudMusic')
f.close()
def get_img(url,songstr): ##保存圖片
#print '##正在讀取圖片##'
#print url
urlStream=urllib.urlopen(url)
htmlString=urlStream.read()
#print htmlString
if( len(htmlString)!=0 ):
patternString=r'http://p1.music.126.net/.*?.jpg'
searchPattern=re.compile(patternString)
imgUrlList=searchPattern.findall(htmlString)
imgUrl =imgUrlList[0]
#print imgUrl
if( len(imgUrl)!= 0 ):
urllib.urlretrieve(imgUrl,'E:\\music\\' + songstr + '.jpg')
# 設置歌曲的信息
def setSongInfo(song):
url = BASE_URL + 'song?id=' + str(song.id)
url.decode('utf-8')
soup = BeautifulSoup(_session.get(url).content)
strArr = soup.title.string.split(' - ')
song.singer = strArr[1]
name = strArr[0].encode('utf-8')
song.name = name
songstr = strArr[0]+ ' - '+ strArr[1]
songstr = songstr.replace('/',' ')
song.lrc = get_lyric_by_music_id(song.id,songstr)
song.img = get_img(url,songstr)
# 獲取符合條件的歌曲列表
def getSongList():
print ' ##正在爬取歌曲編號... ##'
songIdList = getSongIdList()
print ' ##爬取歌曲編號完成,共計爬取到' + str(len(songIdList)) + '首##'
songList=[]
for id in songIdList[0:]:
song = matchSong(id)
if None != song:
setSongInfo(song)
songList.append(song)
print '成功匹配一首{名稱:', song.name, ' - ', song.singer, '}'
# print ' ##爬取完成,符合條件的的共計' + str(len(songList)) + '首##'
return songList
def main():
songList = getSongList()
if __name__ == '__main__':
main()
過程截圖
運行過程
結果
(這里我很慫的把歌手名去掉了因為斜杠的問題解決不掉)
迷之操作
格式工廠轉圖片格式 + 拖把更名器改名……
我想知道這個失敗是什么鬼……
看起來是按順序操作的……朕心甚慰……
最后還是有一部分是手動調的因為改名軟件對于一些特殊字符會出bug……
其他問題
python里的字符格式還是不太懂
然后存文件的時候格式是'歌曲名 - 歌手名.txt'或者jpg,要是歌手名有\分隔會出問題……
反正就是還有一些問題orz
17.10.7
對于斜杠的處理是 替換成空格= =然后還有一些特殊的組合會出問題
總結
以上是生活随笔為你收集整理的python soup歌词_【python】 爬取网易云音乐 专辑图片+歌词的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 即时通讯websocket原码下载
- 下一篇: 中国大学moocpython程序设计答案