用python写什么代码可以下载一首歌曲
时间: 2024-02-01 08:01:19 浏览: 101
要用Python写一个可以下载一首歌曲的代码,可以使用Python的requests库来实现。以下是一个简单的实现:
```python
import requests
def download_song(url, saving_path):
response = requests.get(url)
if response.status_code == 200:
with open(saving_path, 'wb') as file:
file.write(response.content)
print("歌曲下载成功!")
else:
print("无法下载歌曲。")
# Example usage
url = "https://example.com/song.mp3" # 歌曲的URL链接
saving_path = "path/to/save/song.mp3" # 歌曲保存的路径
download_song(url, saving_path)
```
在这个例子中,我们定义了一个名为`download_song`的函数,它接收歌曲的URL链接和保存路径作为参数。函数使用requests库发送GET请求来下载歌曲。如果响应状态码为200,表示请求成功,我们把响应的内容写入指定的保存路径,从而完成歌曲的下载。
你只需要将`url`和`saving_path`参数替换为实际的URL链接和保存路径,就能成功下载歌曲。请确保你有合法的许可来下载该歌曲。
相关问题
python写一个可以爬取音乐的代码
### 回答1:
这是一段爬取音乐的简单 Python 代码:
```python
import requests
from bs4 import BeautifulSoup
# 请求网页
url = "https://music.163.com/playlist?id=3778678"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
res = requests.get(url, headers=headers)
# 解析网页
soup = BeautifulSoup(res.text, 'html.parser')
# 查找音乐信息
music_list = soup.select('.f-hide a')
for music in music_list:
print(music.getText())
```
此代码爬取的是网易云音乐中某个歌单的信息,使用了requests库和beautifulsoup库,需要在终端中运行。
请注意使用爬虫爬取网站的数据时需要遵循网站的相关协议和规定。
### 回答2:
以下是一个使用Python编写的爬取音乐的代码示例:
```python
import requests
from bs4 import BeautifulSoup
def get_music_list(keyword):
url = f"https://www.example.com/search?keywords={keyword}"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
music_list = []
results = soup.find_all('div', {'class': 'music-item'})
for result in results:
title = result.find('h2', {'class': 'title'}).text.strip()
artist = result.find('p', {'class': 'artist'}).text.strip()
music_list.append({'title': title, 'artist': artist})
return music_list
def download_music(url, file_path):
response = requests.get(url)
with open(file_path, 'wb') as file:
file.write(response.content)
if __name__ == "__main__":
keyword = input("请输入要搜索的音乐关键字:")
music_list = get_music_list(keyword)
print(f"共找到{len(music_list)}首符合条件的音乐:")
for index, music in enumerate(music_list):
print(f"{index + 1}. 标题:{music['title']},艺术家:{music['artist']}")
# 假设下载链接在music字典的'download_url'键中保存
download_url = music['download_url']
file_path = f"music{index + 1}.mp3"
download_music(download_url, file_path)
print(f"音乐已下载保存为:{file_path}")
```
这段代码通过向音乐搜索网站发送GET请求,获取搜索结果页面的HTML内容,并使用BeautifulSoup解析HTML,提取出音乐的标题和艺术家信息。然后,根据用户输入的关键字,获取音乐列表。接下来,代码迭代音乐列表,并下载每首歌曲的音乐文件到本地。在代码中,假设下载链接保存在音乐字典的`download_url`键中,下载的音乐文件将保存为`music1.mp3`、`music2.mp3`等。
### 回答3:
import requests
from bs4 import BeautifulSoup
# 定义爬取音乐的函数
def crawl_music(keyword):
url = f"https://music.example.com/search?keyword={keyword}" # 替换为实际的音乐网站链接
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/58.0.3029.110 Safari/537.3"
} # 添加User-Agent以伪装浏览器请求
response = requests.get(url, headers=headers) # 发送GET请求
soup = BeautifulSoup(response.text, "html.parser") # 解析网页
music_list = soup.find_all("a", class_="music") # 根据实际网页结构找到音乐链接标签
for music in music_list:
music_name = music.text # 获取音乐名称
music_url = music["href"] # 获取音乐链接
print("音乐名称:" + music_name)
print("音乐链接:" + music_url)
print("--------")
# 调用函数进行音乐爬取
crawl_music("周杰伦") # 以"周杰伦"为关键词爬取音乐链接
写一段python代码爬取并下载QQ音乐周杰伦的20首歌
由于QQ音乐官方网站进行了反爬虫限制,因此本文提供的代码仅供学习参考,不保证一定能够成功运行。
```python
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
url = 'https://y.qq.com/n/yqq/singer/0025NhlN2yWrP4.html'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
song_list = soup.find_all('span', class_='songlist__songname_txt')
for i in range(20):
song_name = song_list[i].get_text()
song_id = song_list[i].find('a')['href'].split('/')[-1].split('.')[0]
download_url = f'https://u.y.qq.com/cgi-bin/musicu.fcg?data=%7B%22req_0%22%3A%7B%22module%22%3A%22vkey.GetVkeyServer%22%2C%22method%22%3A%22CgiGetVkey%22%2C%22param%22%3A%7B%22guid%22%3A%221234567890%22%2C%22songmid%22%3A%5B%22{song_id}%22%5D%2C%22songtype%22%3A%5B0%5D%2C%22uin%22%3A%220%22%2C%22platform%22%3A%2220%22%2C%22loginflag%22%3A1%2C%22hostUin%22%3A%220%22%7D%7D%2C%22comm%22%3A%7B%22uin%22%3A0%2C%22format%22%3A%22json%22%2C%22ct%22%3A24%2C%22cv%22%3A0%7D%7D'
download_response = requests.get(download_url, headers=headers)
download_json = download_response.json()
download_link = download_json['req_0']['data']['midurlinfo'][0]['purl']
if download_link:
with open(f'{song_name}.m4a', 'wb') as f:
f.write(requests.get(f'https://isure.stream.qqmusic.qq.com/{download_link}', headers=headers).content)
print(f'{song_name}下载成功')
else:
print(f'{song_name}下载失败')
```
解析:
首先,我们使用requests库和BeautifulSoup库对QQ音乐周杰伦的歌曲页面进行请求和解析,得到歌曲列表。
然后,我们通过循环遍历歌曲列表,获取每首歌的名称和ID,并使用下载链接API获取每首歌的下载链接。
最后,我们使用requests库下载每首歌,并将其保存到本地。如果下载链接获取失败,则打印下载失败的提示信息。
阅读全文