引言网易云音乐作为国内领先的在线音乐平台,拥有海量的歌曲和用户评论。其中,热门评论往往能够反映出歌曲的受欢迎程度和用户情感。然而,手动点赞和收藏热门评论无疑是一项费时费力的工作。本文将介绍如何使用Py...
网易云音乐作为国内领先的在线音乐平台,拥有海量的歌曲和用户评论。其中,热门评论往往能够反映出歌曲的受欢迎程度和用户情感。然而,手动点赞和收藏热门评论无疑是一项费时费力的工作。本文将介绍如何使用Python高效抓取网易云音乐的热评,并实现一键收藏功能,让你告别手动点赞。
以某首歌曲的热评页面为例,我们可以看到评论数据通常以JSON格式嵌入在页面的JavaScript代码中。以下是页面中的一部分代码示例:
// 网易云音乐热评页面JavaScript代码片段
var hotComments = { "hotCommentTags": [ // 热门标签数据 ], "comments": [ // 热门评论数据 ]
};以下是一个使用Python抓取网易云音乐热评的示例代码:
import requests
from bs4 import BeautifulSoup
def get_hot_comments(song_id): url = f"https://music.163.com/api/v1/resource/comments/R_SO_4_{song_id}" 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) data = response.json() comments = data.get("comments", []) return comments
# 示例:抓取歌曲ID为123456的热评
song_id = 123456
hot_comments = get_hot_comments(song_id)
for comment in hot_comments: print(comment)我们可以将抓取到的评论数据存储到本地文件中,例如:
def save_comments_to_file(comments, filename): with open(filename, "w", encoding="utf-8") as f: for comment in comments: f.write(str(comment) + "\n")
# 示例:将抓取到的评论保存到文件
save_comments_to_file(hot_comments, "hot_comments.txt")由于网易云音乐的热评页面中并没有直接的API接口用于点赞和收藏,因此我们需要模拟用户的操作。以下是一个简单的示例:
def like_comment(comment_id): url = f"https://music.163.com/api/v1/comment/like" 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" } data = { "commentId": comment_id, "type": 1 } response = requests.post(url, headers=headers, data=data) return response.json()
# 示例:为ID为123456的评论点赞
like_response = like_comment(123456)
print(like_response)通过以上步骤,我们可以使用Python高效抓取网易云音乐的热评,并实现一键收藏功能。需要注意的是,由于网易云音乐的反爬虫机制,以上代码可能需要根据实际情况进行调整。同时,我们在进行爬虫操作时,应遵守相关法律法规和网站的使用协议,尊重用户隐私和版权。