python網易雲音樂下載器爬取全網音樂
完整代碼:
import tkinter as tk
import os
import urllib
from pydoc import text
from urllib.request import urlretrieve
from selenium import webdriver
#https://music.163.com/#/search/m/?s=%E7%BB%BF%E8%89%B2&type=1
def song_load(item):
song_id = item['song_id']
song_name = item['song_name']
song_url = 'http://music.163.com/song/media/outer/url?id={}.mp3'.format(song_id)
os.makedirs('music',exist_ok=True)
path = '/Users/baby/Desktop/網易雲音樂/music/{}.mp3'.format(song_name)
#文本框
t1.insert(tk.END,'歌曲:{} 正在下載中!'.format(song_name))
#文本框滾動
t1.see(tk.END)
#文本框更新
t1.update()
#下載
urlretrieve(song_url,path)
t1.insert(tk.END,'歌曲:{} 下載完成啦!'.format(song_name))
t1.see(tk.END)
t1.update()
#獲取歌曲id
def get_musci_name():
music_name = e1.get()
music_name = urllib.parse.quote(music_name)
url = 'https://music.163.com/#/search/m/?s={}&type=1'.format(music_name)
driver = webdriver.Chrome()
driver.get(url=url)
driver.switch_to.frame('g_iframe')
req = driver.find_element_by_id('m-search')
a_id = req.find_element_by_xpath('.//div[@class="item f-cb h-flag "]/div[2]//a').get_attribute('href')
song_id = a_id.split('=')[-1]
song_name = req.find_element_by_xpath('.//div[@class="item f-cb h-flag "]/div[2]//b').get_attribute('title')
item = {}
item['song_id'] = song_id
item['song_name'] = song_name
song_load(item)
root = tk.Tk()
root.title('網易雲音樂下載器')
root.geometry('500x300')
l1 = tk.Label(root,text = '請輸入要下載的歌曲:',font=('蘭亭黑',15))
l1.grid(row=0,column=0)
e1= tk.Entry(root,font=('隸書', 15))
e1.grid(row=0,column=1)
t1 = tk.Listbox(root,font=('微軟雅黑',20),width=38,height=8)
t1.grid(row=1,columnspan=2)
b1 = tk.Button(root,text = '開始下載',command=get_musci_name)
b1.grid(row=2, column=0, sticky=tk.W)
b2 = tk.Button(root,text = '退出程序',command=root.quit)
b2.grid(row=2, column=1, sticky=tk.E)
root.mainloop()