import requests
import json
import csv
url = 'https://music.163.com/api/v1/resource/comments/R_SO_4_{}?limit=20&offset={}'
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'
}
# 这里的id是网易云歌曲链接中的数字,可以根据不同的歌曲进行更改
song_id = '480840953'
# 存储评论的列表
comments_list = []
# 循环获取评论
for i in range(5):
url_request = url.format(song_id, i*20)
response = requests.get(url_request, headers=headers)
result = json.loads(response.text)
comments = result['comments']
for comment in comments:
comment_time = comment['time'] # 评论时间
comment_like = comment['likedCount'] # 点赞数
comment_content = comment['content'] # 评论内容
comment_nickname = comment['user']['nickname'] # 用户昵称
comment_info = [comment_time, comment_like, comment_content, comment_nickname] # 存储评论信息的列表
comments_list.append(comment_info)
with open('comments.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['评论时间', '点赞数', '评论内容', '用户昵称']) # 写入表头
for comment in comments_list:
writer.writerow(comment) # 写入评论信息
完整代码如下: