爬取網易雲音樂MP3連結指令碼
阿新 • • 發佈:2019-01-05
程式碼部分
#Python 3.5
#Author: A_lPha
#Blog: http://blog.csdn.net/a_lpha
import json
from urllib.request import urlopen
from urllib.error import HTTPError
print("*" * 8,"網易雲音樂下載器", "*" * 8,"\n")
ID = input('請輸入歌曲ID:\n>>> ')
url = "http://music.163.com/api/song/detail/?ids=[" + ID + "]"
html = urlopen(url).read().decode("utf-8" )
rejson = json.loads(html)
for name in rejson['songs']:
print('歌曲ID: ',name['id'])
print('歌曲名稱: ',''.join(name['name']))
print('歌手: ',''.join(names['name'] for names in name['artists']))
print('mp3連結: ',name['mp3Url'])
num = int(input('\n是否下載?(輸入1下載該歌曲,輸入其他數字關閉程式.)\n'))
if num == 1 :
try:
f = open(str(''.join(name['name']) + "-" + ''.join(names['name'] for names in name['artists'])) + ".mp3", "wb")
req = urlopen(name['mp3Url'])
buf = req.read()
f.write(buf)
f.close()
print("已儲存")
except HTTPError as e:
print("遇到錯誤啦! 錯誤程式碼是這個: \n" ,">>>>>>",e,"<<<<<<","\n我猜這是付費歌曲的'ID',可能是網站不讓下載吧!")
elif num != 1:
print("已關閉")
找網易雲音樂歌曲的ID方法,在網易雲音樂搜尋到該歌曲,開啟播放頁面,在瀏覽器位址列後顯示該歌曲ID。
一般情況下可以找到歌曲的連結,付費歌曲也可以找到連結,但是返回404錯誤。
程式碼很簡單,現在還沒發現其他問題。
==================================更新==================================
#Python 3.5
#Author: A_lPha
#Blog: http://blog.csdn.net/a_lpha
import json
import time
from urllib.request import urlopen
from urllib.error import HTTPError
print("*" * 8,"網易雲音樂下載器", "*" * 8,"\n")
def getId():
try:
ID = int(input('請輸入歌曲ID:\n>>> '))
print("正在查詢,請稍後...\n")
time.sleep(0.9)
return ID
except:
print("請輸入正確的ID!\n")
getId()
def getInformations(ID):
print("--"*4,"查詢結果","--"*4)
try:
ID = str(ID)
url = "http://music.163.com/api/song/detail/?ids=["+ID+"]"
html = urlopen(url).read().decode("utf-8")
rejson = json.loads(html)
for informations in rejson['songs']:
print('歌曲ID: ', informations['id'])
print('歌曲名稱: ', ''.join(informations['name']))
print('歌手: ', ''.join(names['name'] for names in informations['artists']))
print('mp3連結: ', informations['mp3Url'])
song = ''.join(informations['name'])
name = ''.join(names['name'] for names in informations['artists'])
mp3url = informations['mp3Url']
return song,name,mp3url
except:
print("這個可能不是正確的ID哦!重新試試吧。")
id = getId()
song, name, mp3url = getInformations(id)
getUrl(song, name, mp3url)
def getUrl(song,name,mp3url):
print("-"*9, "下載", "-"*9)
num = int(input('是否下載?(輸入1下載該歌曲,輸入其他數字關閉程式.)\n'))
if num == 1:
try:
filename = str(song + "-" + name)
with open(filename + ".mp3", "wb") as mp:
infor = urlopen(mp3url).read()
mp.write(infor)
print("已儲存!")
except HTTPError as e:
print("遇到錯誤啦! 錯誤程式碼是這個: \n", ">>>>>>", e, "<<<<<<", "\n我猜這是付費歌曲的'ID',可能是網站不讓下載吧!")
elif num != 1:
print("已關閉。")
id = getId()
song, name, mp3url = getInformations(id)
getUrl(song, name, mp3url)
這段程式碼處理了異常,介面也清晰了許多。不過程式碼還是有些臃腫。