Python爬取酷狗音乐松田圣子歌曲:简单示例与代码

本文提供一个使用Python爬取酷狗音乐松田圣子歌曲的简单示例,包括获取歌曲列表和下载歌曲功能。代码清晰易懂,适合学习Python网络爬虫入门。

代码示例

import requests
from bs4 import BeautifulSoup

def get_song_list(artist_name): url = f'https://www.kugou.com/yy/singer/home/{artist_name}.html' 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' } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') song_list = soup.find_all('a', {'class': 'song_name'}) return song_list

def download_song(song_url, file_name): response = requests.get(song_url) with open(f'{file_name}.mp3', 'wb') as f: f.write(response.content)

获取松田圣子的歌曲列表

song_list = get_song_list('松田圣子')

输出歌曲列表

print("松田圣子的歌曲列表:") for song in song_list: print(song.text)

下载选择的歌曲

song_index = int(input("请输入要下载的歌曲序号: ")) if song_index >= 0 and song_index < len(song_list): song_name = song_list[song_index].text song_url = song_list[song_index]['href'] download_song(song_url, song_name) print(f"成功下载歌曲:{song_name}") else: print("输入的歌曲序号无效。")

代码解释

在这个示例中,我们首先定义了两个函数:get_song_list用于获取松田圣子的歌曲列表,download_song用于下载选定的歌曲。

然后,我们通过get_song_list函数获取松田圣子的歌曲列表,并输出到控制台供选择。用户输入要下载的歌曲序号后,我们使用download_song函数下载选定的歌曲,并保存为MP3文件。

请注意,这只是一个简单的示例,实际爬取网页数据时可能需要处理一些异常情况和其他细节。


原文地址: https://www.cveoy.top/t/topic/pPIc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录