可以用Python写一个爬取网易云音乐的歌曲并把他保存在D盘的程序并且界面都是中文的吗
是的,可以使用Python编写一个爬取网易云音乐歌曲并将其保存在D盘的程序。以下是一个简单的示例:
import requests
import os
from bs4 import BeautifulSoup
def get_song_list(keyword):
# 构造请求URL
url = f'http://music.163.com/search/'
params = {
'type': 1,
's': keyword
}
# 发送请求获取页面内容
response = requests.get(url, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析页面获取歌曲信息
song_list = []
for item in soup.select('.srchsongst .item'):
song_name = item.select_one('.w0').text.strip()
artist = item.select_one('.w1').text.strip()
song_list.append((song_name, artist))
return song_list
def download_song(song_name, artist, save_path):
# 构造搜索关键字
keyword = f'{song_name} {artist}'
# 构造请求URL
url = f'http://music.163.com/search/'
params = {
'type': 1,
's': keyword
}
# 发送请求获取页面内容
response = requests.get(url, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析页面获取歌曲下载链接
song_url = soup.select_one('.srchsongst .item').get('href')
song_id = song_url.split('=')[-1]
download_url = f'http://music.163.com/song/media/outer/url?id={song_id}.mp3'
# 下载歌曲
response = requests.get(download_url)
if response.status_code == 200:
file_path = os.path.join(save_path, f'{song_name}-{artist}.mp3')
with open(file_path, 'wb') as file:
file.write(response.content)
print(f'歌曲{song_name}-{artist}下载完成!')
else:
print(f'下载歌曲{song_name}-{artist}失败!')
if __name__ == '__main__':
keyword = input('请输入要搜索的歌曲关键字:')
save_path = 'D:\\' # 修改保存路径为D盘根目录
song_list = get_song_list(keyword)
for song_name, artist in song_list:
download_song(song_name, artist, save_path)
此示例使用了requests库发送HTTP请求,BeautifulSoup库进行页面解析。你需要安装这两个库才能运行此程序。
请注意,网易云音乐有可能会对爬虫进行限制,因此请遵守相关网站的使用规定,不要过度使用爬虫程序
原文地址: https://www.cveoy.top/t/topic/h3LP 著作权归作者所有。请勿转载和采集!