|
发表于 2024-5-1 06:57:49
|
显示全部楼层
非常抱歉,我之前的代码中没有指定保存路径为E:\Temp。下面是修改后的代码示例,使用 PySide6 创建界面,并实现音乐下载并保存到 E:\Temp 目录的功能:
- import os
- import requests
- from bs4 import BeautifulSoup
- from PySide6.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QLineEdit, QPushButton, QMessageBox, QFileDialog
- class MusicDownloader(QWidget):
- def __init__(self):
- super().__init__()
- self.setWindowTitle("音乐下载器")
-
- # 创建界面组件
- self.search_label = QLabel("请输入要搜索的歌曲名称:")
- self.search_input = QLineEdit()
- self.download_button = QPushButton("下载")
-
- # 布局
- layout = QVBoxLayout()
- layout.addWidget(self.search_label)
- layout.addWidget(self.search_input)
- layout.addWidget(self.download_button)
-
- self.setLayout(layout)
-
- # 绑定按钮点击事件
- self.download_button.clicked.connect(self.download_music)
-
- def download_music(self):
- # 获取输入的歌曲名称
- song_name = self.search_input.text()
-
- # 构造搜索链接
- search_url = f'https://music.163.com/#/search/m/?s={song_name}&type=1'
-
- # 发送HTTP GET请求获取搜索页面内容
- response = requests.get(search_url)
- html = response.text
-
- # 使用BeautifulSoup解析页面
- soup = BeautifulSoup(html, 'html.parser')
-
- # 找到搜索结果中的第一个歌曲链接
- song = soup.find('a', {'class': 'tit'})
-
- # 如果没有找到歌曲链接,则弹出错误提示框
- if song is None:
- QMessageBox.critical(self, "错误", f"未找到歌曲:{song_name}")
- return
-
- # 提取歌曲链接和歌曲名称
- href = song['href']
- name = song.text
-
- # 构造完整的歌曲链接
- song_url = 'https://music.163.com' + href
-
- # 发送HTTP GET请求获取歌曲页面内容
- song_response = requests.get(song_url)
- song_html = song_response.text
-
- # 使用BeautifulSoup解析歌曲页面
- song_soup = BeautifulSoup(song_html, 'html.parser')
-
- # 找到包含音乐链接的标签
- music = song_soup.find('a', {'class': 'u-btni u-btni-addply f-fl'})
-
- # 提取音乐链接
- mp3_url = music['data-res-url']
-
- # 发送HTTP GET请求获取音乐文件
- mp3_response = requests.get(mp3_url)
-
- # 弹出保存文件对话框,选择保存路径
- save_path = QFileDialog.getSaveFileName(self, '保存音乐', os.path.join('E:', 'Temp', f'{name}.mp3'), 'MP3 Files (*.mp3)')[0]
-
- # 如果用户取消保存,则返回
- if not save_path:
- return
-
- # 保存音乐文件到指定路径
- with open(save_path, 'wb') as f:
- f.write(mp3_response.content)
-
- QMessageBox.information(self, "成功", f"音乐下载完成")
- if __name__ == "__main__":
- app = QApplication()
- window = MusicDownloader()
- window.show()
- app.exec()
复制代码
在该代码中,使用 `os.path.join()` 函数构造了保存路径为 E:\Temp\ 的绝对路径。同时,使用 `QFileDialog.getSaveFileName()` 弹出文件保存对话框,方便用户选择保存路径和文件名。
希望这次能够满足你的需求!如有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|