下載歌曲的時候嫌麻煩?打造專屬你的音樂下載器

 

 

前言

前面已經做出了一個只屬於自己的音樂播放器,那怎麼能沒有一個音樂下載器呢

之前大家有沒有過從電腦上下載歌曲MP3文件放到手機內存卡的經歷,隨着時代發展,現在的各大音樂軟件已經成爲播放器,下載音樂是要收費的,現在教大家從零開始可以通過python通過爬蟲爬取音樂,教大家打造自己的音樂下載器。

知識點:
1.python基礎知識
2.requests庫
3.urllib庫
4.BeautifulSoup

環境:

windows + pycharm + python3

適合零基礎的同學

1、導入工具

import os
from urllib.request import urlretrieve
from tkinter import *
import requests
from selenium import webdriver

2、界面

# 創建界面
root = Tk()
# 標題
root.title('網易雲音樂下載器')
# 設置窗口大小
root.geometry('560x450')

# 標籤控件
label = Label(root,text='請輸入歌曲名稱:',font=('華文行楷',20))
# 標籤定位
label.grid()
# 輸入框
entry = Entry(root,font=('隸書',20))
entry.grid(row=0,column=1)
# 列表框
text = Listbox(root,font=('楷書',16),width=50,heigh=15)
text.grid(row=1,columnspan=2)  # 橫跨
# 開始按鈕
button = Button(root,text='開始下載',font=('隸書',15),command=get_music_name)    #command
button.grid(row=2,column=0,sticky=W)  #sticky  對齊方式  W E N S
# 退出按鈕
button1 = Button(root,text='退出程序',font=('隸書',15),command=root.quit)    #command
button1.grid(row=2,column=1,sticky=E)

# 顯示界面
root.mainloop()

運行代碼,只得到一個界面

 

 

3、功能

爬取網易雲音樂

 

# https://music.163.com/#/search/m/?s=%E7%9B%97%E5%B0%86%E8%A1%8C&type=1
# http://music.163.com/song/media/outer/url?id=574566207.mp3

headers = {
    'Referer': 'https://music.163.com/',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}

下載歌曲

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 = 'music\{}.mp3'.format(song_name)
    # 文本框
    text.insert(END,'歌曲:{},正在下載...'.format(song_name))
    # 文本框滾動
    text.see(END)
    # 更新
    text.update()
    # 下載
    urlretrieve(song_url,path)
    # 文本框
    text.insert(END, '下載完畢:{},請試聽...'.format(song_name))
    # 文本框滾動
    text.see(END)
    # 更新
    text.update()

搜索歌曲名稱

def get_music_name():
    name = entry.get()
    url  = 'https://music.163.com/#/search/m/?s={}&type=1'.format(name)
    # 隱藏瀏覽器
    option = webdriver.ChromeOptions()
    option.add_argument('--headless')
    driver = webdriver.Chrome(chrome_options=option)
    driver.get(url=url)
    driver.switch_to.frame('g_iframe')

    # 獲取歌曲id
    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")
    print(a_id)
    song_id = a_id.split('=')[-1]
    print(song_id)
    # 獲取歌曲名
    song_name = req.find_element_by_xpath('.//div[@class="item f-cb h-flag  "]/div[2]//b').get_attribute("title")
    print(song_name)
    item = {}
    item['song_id'] = song_id
    item['song_name'] = song_name

    driver.quit() # 退出瀏覽器
    song_load(item)

最後運行代碼,效果如下圖

如果你處於想學Python或者正在學習Python,Python的教程不少了吧,但是是最新的嗎?說不定你學了可能是兩年前人家就學過的內容,在這小編分享一波2020最新的Python教程。獲取方式,私信小編 “ 資料 ”,即可免費獲取哦!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章