python爬取网易云音乐歌曲
时间: 2023-09-24 11:03:40 浏览: 290
python爬取网易云音乐热歌榜实例代码
5星 · 资源好评率100%
好的,以下是一个简单的Python爬虫程序,可以爬取网易云音乐中某个歌手的所有歌曲信息:
```python
import requests
import json
# 歌手ID
artist_id = '6452'
# 请求头
headers = {
'Referer': 'https://music.163.com/',
'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'
}
# 获取歌手的所有专辑信息
def get_album_info(artist_id):
url = 'https://music.163.com/api/artist/albums/%s' % artist_id
response = requests.get(url, headers=headers)
result = json.loads(response.text)
return result['hotAlbums']
# 获取某个专辑的所有歌曲信息
def get_song_info(album_id):
url = 'https://music.163.com/api/album/%s' % album_id
response = requests.get(url, headers=headers)
result = json.loads(response.text)
return result['album']['songs']
# 获取某个歌曲的详细信息
def get_song_detail(song_id):
url = 'https://music.163.com/api/song/detail/?id=%s&ids=[%s]' % (song_id, song_id)
response = requests.get(url, headers=headers)
result = json.loads(response.text)
return result['songs'][0]
# 爬取歌手的所有歌曲信息
def crawl_songs(artist_id):
songs = []
albums = get_album_info(artist_id)
for album in albums:
album_id = album['id']
album_name = album['name']
for song in get_song_info(album_id):
song_id = song['id']
song_name = song['name']
song_detail = get_song_detail(song_id)
song_info = {
'song_id': song_id,
'song_name': song_name,
'album_id': album_id,
'album_name': album_name,
'artist_name': song_detail['artists'][0]['name'],
'publish_time': song_detail['album']['publishTime'],
'duration': song_detail['duration']
}
songs.append(song_info)
return songs
# 打印结果
for song in crawl_songs(artist_id):
print(song)
```
以上程序会输出歌手某个歌手所有歌曲的ID,歌曲名,所在专辑的ID和专辑名,演唱者名字,发行时间以及时长等信息。注意,上述代码中的歌手ID需要替换为实际歌手的ID才能正常运行。
阅读全文