日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python soup歌词_【python】 爬取网易云音乐 专辑图片+歌词

發(fā)布時(shí)間:2023/12/29 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python soup歌词_【python】 爬取网易云音乐 专辑图片+歌词 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

要求

下載一百首歌曲,相關(guān)圖片以及相關(guān)文字信息

存儲方式分別為:

.mp3

.txt

.png

比如第一首歌曲相關(guān)信息為001.mp3\001.txt\001.png

覺得像是小朋友的抄寫作業(yè)有沒有……

想試試看爬-雖然我也不知道行不行

思路

一開始的想法是全都直接根據(jù)歌單獲取歌曲的ID,然后每首歌都按那個(gè)格式001.mp3\001.txt\001.png存下來

后來發(fā)現(xiàn)我好像做不到直接下mp3……因?yàn)樵诰W(wǎng)頁版一點(diǎn)會(huì)跳出來請?jiān)赑C版下載(咦所以結(jié)果我也不知道怎么操作……)

然后計(jì)劃就變成了 - 爬圖片+歌詞,命名成和音樂同個(gè)格式,然后按名字排序之后就可以用改名軟件批量直接改成這個(gè)樣子了(自以為很機(jī)智)

雖然本人對python的理解還停留在曾經(jīng)因作業(yè)要求爬過一次的莎士比亞全集……

準(zhǔn)備

軟件

如果你和我一樣智障的話你可能需要如下資料

然后不一定都有用……因?yàn)槲沂且恢痹诟膭e人的代碼……

exprcted an indented block - 調(diào)整縮進(jìn)

具體操作

美湯(程序員都是吃貨系列

先對著一個(gè)歌單把ID爬下來

然后再對著ID爬各種……(只能想到這樣了)

具體實(shí)現(xiàn)

應(yīng)該可以從如下代碼中看到以上一些參考文獻(xiàn)的痕跡(捂臉)

雖然拼湊痕跡有點(diǎn)明顯orz反正能大概實(shí)現(xiàn)功能已經(jīng)很滿意了

讀取歌單

# 爬取某歌單的所有歌曲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)

# 去一下重復(fù)的歌曲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):#定義一個(gè)函數(shù),通過音樂的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:#部分歌曲沒有歌詞,這里引入一個(gè)異常

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)

# 去一下重復(fù)的歌曲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):#定義一個(gè)函數(shù),通過音樂的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:#部分歌曲沒有歌詞,這里引入一個(gè)異常

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')

# 設(shè)置歌曲的信息

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 ' ##爬取歌曲編號完成,共計(jì)爬取到' + 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 ' ##爬取完成,符合條件的的共計(jì)' + str(len(songList)) + '首##'

return songList

def main():

songList = getSongList()

if __name__ == '__main__':

main()

過程截圖

運(yùn)行過程

結(jié)果

(這里我很慫的把歌手名去掉了因?yàn)樾备艿膯栴}解決不掉)

迷之操作

格式工廠轉(zhuǎn)圖片格式 + 拖把更名器改名……

我想知道這個(gè)失敗是什么鬼……

看起來是按順序操作的……朕心甚慰……

最后還是有一部分是手動(dòng)調(diào)的因?yàn)楦拿浖τ谝恍┨厥庾址麜?huì)出bug……

其他問題

python里的字符格式還是不太懂

然后存文件的時(shí)候格式是'歌曲名 - 歌手名.txt'或者jpg,要是歌手名有\(zhòng)分隔會(huì)出問題……

反正就是還有一些問題orz

17.10.7

對于斜杠的處理是 替換成空格= =然后還有一些特殊的組合會(huì)出問題

總結(jié)

以上是生活随笔為你收集整理的python soup歌词_【python】 爬取网易云音乐 专辑图片+歌词的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。