爬取网易云音乐评论区的完整Python代码示例
时间: 2025-07-04 19:01:01 浏览: 2
为了爬取网易云音乐评论区的热评内容,需要处理网页请求、加密参数以及解析返回的数据。以下是一个完整的Python代码示例,展示了如何实现这一目标。
该代码基于对网易云音乐评论接口的分析,使用了`requests`库发起HTTP请求,并通过模拟加密函数生成所需的参数。此方法适用于学习和练习目的,请注意遵守相关法律法规及网站的使用条款。
### 爬虫实现步骤
1. **确定目标URL**:网易云音乐评论接口。
2. **构造加密参数**:包括`encText`和`encSecKey`。
3. **发送POST请求**:获取评论数据。
4. **解析JSON响应**:提取所需信息。
```python
import base64
import json
import random
import requests
from Crypto.Cipher import AES
def aes_encrypt(text, key):
"""
AES加密函数
:param text: 待加密文本
:param key: 密钥
:return: 加密后的字符串
"""
pad = 16 - len(text) % 16
text += pad * chr(pad)
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, b'0102030405060708')
encrypted_text = cipher.encrypt(text.encode('utf-8'))
return base64.b64encode(encrypted_text).decode('utf-8')
def rsa_encrypt(public_key, modulus, text):
"""
RSA加密函数
:param public_key: 公钥
:param modulus: 模数
:param text: 待加密文本
:return: 加密后的字符串
"""
text = text[::-1]
result = pow(int.from_bytes(text.encode(), 'big'), int(public_key, 16), int(modulus, 16))
return format(result, 'x').zfill(256)
def get_enc_params(text):
"""
获取加密参数
:param text: 原始文本
:return: encText 和 encSecKey
"""
public_key = '010001'
modulus = '00e0b509f6259df8642dbc35662901477df2fa0720936d5da78c7a91f71f9e0d' \
'eaf3a08eac8a815b4bacc9049ad32ccab8810bf41ed4eea01f04ce9ddeaae793'
nonce = '0CoJUm6Qyw8WgYV1'
# 第一次AES加密
enc_text = aes_encrypt(text, nonce)
# 第二次AES加密
sec_key = rsa_encrypt(public_key, modulus, ''.join(random.choice('0123456789') for _ in range(16)))
enc_text = aes_encrypt(enc_text, sec_key)
return enc_text, sec_key
def fetch_comments(song_id, offset=0, limit=20):
"""
抓取指定歌曲的评论
:param song_id: 歌曲ID
:param offset: 分页偏移量
:param limit: 每页数量
:return: 评论列表
"""
url = 'https://music.163.com/weapi/comment/resource/comments/get?csrf_token='
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://music.163.com/',
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
"rid": f"R_SO_4_{song_id}",
"offset": offset,
"total": "true",
"limit": limit,
"csrf_token": ""
}
params = json.dumps(data)
enc_text, sec_key = get_enc_params(params)
post_data = {
'params': enc_text,
'encSecKey': sec_key
}
response = requests.post(url, headers=headers, data=post_data)
comments = []
if response.status_code == 200:
json_response = response.json()
for comment in json_response.get('comments', []):
comments.append({
'user': comment['user']['nickname'],
'content': comment['content'],
'liked_count': comment['likedCount']
})
return comments
# 示例用法
if __name__ == '__main__':
song_id = 186016 # 替换为你想要抓取评论的歌曲ID
comments = fetch_comments(song_id)
for idx, comment in enumerate(comments, start=1):
print(f"{idx}. 用户: {comment['user']}, 赞同数: {comment['liked_count']}")
print(f" 评论: {comment['content']}\n")
```
### 注意事项
- **依赖库安装**:确保安装了`requests`和`pycryptodome`库,可以通过pip安装:
```bash
pip install requests pycryptodome
```
- **合法性**:在实际应用中,请确保你的行为符合网易云音乐的服务条款,并尊重其反爬机制[^1]。
阅读全文
相关推荐

















