Python下载酷狗音乐歌曲

最近想研究一下Python的图形界面,但是因为我的Python版本是2.7,没法用QT,所以试了试wxPython。效果还不错,虽然总体来说不如WPF好用和美观,但是做简单的应用程序足够了。

作为练习,写了一个酷狗的音乐下载器,上代码:

# -*- coding:utf8 -*-

import wx
import urllib

class App(wx.App):
    def OnInit(self):
        frame = wx.Frame(parent = None, title = 'MusicDownloader', pos = (1000, 200), size = (600, 150))
        pathTitle = wx.StaticText(frame, label = "Url链接", pos = (5,8), size = (70, 24) )
        pathText = wx.TextCtrl(frame ,pos = (70, 5), size = (400, 24))
        openButton = wx.Button(frame, label = "下载歌曲", pos=(470, 5), size=(100, 24))
        musicTitle = wx.StaticText(frame, label = "保存歌曲名", pos = (5,43), size = (70, 24))
        musicText = wx.TextCtrl(frame, pos=(70, 40), size=(300, 24))
        tipsTitle = wx.StaticText(frame, label="默认保存在桌面", pos=(5, 80), size=(100, 24))
        tipsTitle.SetForegroundColour('gray')
        def OnClickDownloadBtn(event):
            url = pathText.GetValue()
           
### 使用Python酷狗音乐平台下载音乐 为了实现从酷狗音乐平台下载音乐的功能,可以按照如下方法构建程序。此过程涉及使用`requests`库发送HTTP请求获取页面数据以及利用正则表达式或其他解析工具来处理返回的数据。 #### 安装必要的包 首先安装所需的第三方库,可以通过pip命令完成这些操作: ```bash pip install requests beautifulsoup4 selenium webdriver_manager ``` #### 设置环境与导入模块 准备阶段需要引入相应的Python模块,并配置好Webdriver以便后续自动化控制浏览器访问目标站点。 ```python from selenium import webdriver from bs4 import BeautifulSoup import re import os from urllib.parse import quote_plus as urlencode from webdriver_manager.chrome import ChromeDriverManager ``` #### 构建函数用于搜索歌曲并提供下载链接 定义一个名为`search_song_and_download`的函数接收用户输入作为参数,在线查找匹配项并将结果呈现给使用者选择具体哪一首歌进行下一步动作。 ```python def search_song_and_download(song_name): driver = webdriver.Chrome(ChromeDriverManager().install()) try: encoded_query = urlencode(song_name.encode('gbk')) url = f"https://www.kugou.com/yy/html/search.html#searchType=song&searchKeyWord={encoded_query}" driver.get(url) soup = BeautifulSoup(driver.page_source, 'html.parser') items = soup.find_all('li', class_='item') songs_list = [] for idx, item in enumerate(items[:10], start=1): # 只显示前十个结果供选择 title_tag = item.select_one('.songname .pc_temp_songname a').get_text(strip=True) singer = item.select_one('.singer a').get_text(strip=True).strip() hash_value = re.search(r'data\-hash="(.*?)"', str(item)).group(1) print(f"{idx}. {title_tag} - {singer}") songs_list.append((title_tag, singer, hash_value)) choice = int(input("\n请输入您要下载歌曲编号:")) - 1 selected_title, _, song_hash = songs_list[choice] download_url = get_direct_download_link(song_hash) save_music_file(download_url, selected_title) finally: driver.quit() def get_direct_download_link(hash_code): api_endpoint = "https://wwwapi.kugou.com/yy/index.php" params = { 'r': 'play/getdata', 'hash': hash_code, 'album_id': '', 'dfid': '' } response = requests.post(api_endpoint, data=params) json_data = response.json() return json_data['data']['play_url'] def save_music_file(file_url, filename): music_dir = './music/' if not os.path.exists(music_dir): os.makedirs(music_dir) file_path = os.path.join(music_dir, f'{filename}.mp3'.replace("/", "-").replace("\\", "-")) with open(file_path, 'wb') as file: file.write(requests.get(file_url).content) print(f"\n已成功保存至{file_path}") if __name__ == '__main__': keyword = input("请输入你想下载歌曲名:") search_song_and_download(keyword)[^3] ``` 上述代码实现了基本功能框架,实际应用时可能还需要考虑异常情况下的错误处理机制等问题[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值