python网易云音乐抓取脚本
时间: 2023-10-15 14:04:27 浏览: 144
抓取网易云音乐的脚本如下:
```python
import requests
import json
# 设置请求头信息
headers = {
'Referer': 'https://music.163.com/',
'Host': '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',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9',
}
# 请求接口获取歌曲信息
def get_song_info(song_id):
url = 'https://music.163.com/api/song/detail/?id=' + str(song_id) + '&ids=%5B' + str(song_id) + '%5D'
response = requests.get(url, headers=headers)
song_info = json.loads(response.text)
return song_info
# 解析歌曲信息,获取歌曲名和歌手名
def parse_song_info(song_info):
song_name = song_info['songs'][0]['name']
singer_name = song_info['songs'][0]['artists'][0]['name']
return song_name, singer_name
# 获取歌曲评论
def get_song_comments(song_id):
url = 'https://music.163.com/api/v1/resource/comments/R_SO_4_%s/?rid=R_SO_4_%s&offset=0&total=true&limit=100' % (song_id, song_id)
response = requests.get(url, headers=headers)
comments_info = json.loads(response.text)
comments = [comment['content'] for comment in comments_info['comments']]
return comments
# 主函数,遍历歌单中的歌曲并抓取信息
def main():
song_list_id = '歌单ID' # 此处填写歌单ID
url = 'https://music.163.com/playlist?id=' + song_list_id
response = requests.get(url, headers=headers)
songs_info = json.loads(response.text.split('[')[1].split(']')[0] + ']')
for song_info in songs_info:
song_id = song_info['id']
song_info = get_song_info(song_id)
song_name, singer_name = parse_song_info(song_info)
comments = get_song_comments(song_id)
print('歌曲名:', song_name)
print('歌手名:', singer_name)
print('评论数:', len(comments))
print('评论列表:', comments)
print('\n')
if __name__ == '__main__':
main()
```
使用方法:
1. 将代码中的`歌单ID`替换为你要抓取的歌单ID。
2. 运行脚本,即可抓取歌单中所有歌曲的信息,包括歌曲名、歌手名和评论列表。
阅读全文