用過很多播放器穷当,之前一直是酷我获洲,偶爾QQ阱表。但是網易云音樂出來后毅然變成了他的忠實用戶。精確推薦和樂評都很贊贡珊!安利了不少人入坑最爬。前些日子網易云音樂將精選用戶評論搬上了地鐵,使網易云音樂又火了一把飞崖。因此就想爬取一些歌曲的評論烂叔。
分析
通過抓包分析與評論有關的內容在評論相關的請求在http://music.163.com/weapi/v1/resource/comments/R_SO_4_186016?csrf_token= 這個請求下完成。
網絡請求
如圖我們可以看到有兩個參數(shù)params和encSecKey」掏幔現(xiàn)在如何得到這兩個參數(shù)就變得至關重要蒜鸡。參考知乎https://www.zhihu.com/question/36081767 問題的解答
core.js
core.js
b函數(shù)與asrea為一個函數(shù)胯努,四個參數(shù)分別為:
第一個參數(shù):
first_param = '{rid:"", offset:"0", total:"true", limit:"20", csrf_token:""}'
rid就是R_SO_4_加上歌曲的id(其實這個參數(shù)也是可以沒有的),offset就是(評論頁數(shù)-1) * 20逢防,total在第一頁是true叶沛,其余是false。
第二個參數(shù):010001
第三個參數(shù):00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7
第四個參數(shù):0CoJUm6Qyw8W8jud
第二三四個參數(shù)均為固定值
此時b函數(shù)就是一個AES加密忘朝,經過了兩次加密生成params灰署。其中i為長度為16的一個字符串,可以取定值局嘁。那么此時c函數(shù)生成的encSecKey便為固定值溉箕。
參數(shù)生成完畢即可訪問獲取返回的json數(shù)據。
github地址
代碼如下
#! /usr/bin/python
# -*-coding:utf-8-*-
# Author:zp
from Crypto.Cipher import AES
import base64
import requests
import json
import codecs
import time
# 頭部信息
headers = {
'Host': "music.163.com",
'Accept-Language': "zh-CN,zh;q=0.8",
'Accept-Encoding': "gzip, deflate, sdch",
'Content-Type': "application/x-www-form-urlencoded",#text/html;charset=utf8
'Cookie': "JSESSIONID-WYYY=cd1Rl3VE3QCuWrM1F2p5X2uldz7nID%5CPkiCScp1xwmj%5CQaK1ntkfjHrdsOIPo63qTVSQ%2F31E5R19S8qrlWscJtCZM4fHnp25P%2FHrDweHD91%2FeaFxBD%2Fq6efikdBYg9mDhDAHy0yW23r6iGkCIUE4NGQYNw4oMbmeNiBuf%2BTNfh6MysQ%2B%3A1491229798294; _iuqxldmzr_=32; _ntes_nnid=d805c50ad0597b9a6f15c3a0724ac9f3,1491227998322; _ntes_nuid=d805c50ad0597b9a6f15c3a0724ac9f3; __utma=94650624.196941009.1491227999.1491227999.1491227999.1; __utmb=94650624.8.10.1491227999; __utmc=94650624; __utmz=94650624.1491227999.1.1.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; playerid=36222054",
'Connection': "keep-alive",
'Referer': 'http://music.163.com/'
}
# 設置代理服務器
proxies = {
'http:': 'http://121.232.146.184',
'https:': 'https://144.255.48.197'
}
# offset的取值為:(評論頁數(shù)-1)*20,total第一頁為true悦昵,其余頁為false
# first_param = '{rid:"", offset:"0", total:"true", limit:"20", csrf_token:""}' # 第一個參數(shù)
second_param = "010001" # 第二個參數(shù)
# 第三個參數(shù)
third_param = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
# 第四個參數(shù)
forth_param = "0CoJUm6Qyw8W8jud"
# 獲取參數(shù)
def get_params(page): # page為傳入頁數(shù)
iv = "0102030405060708"
first_key = forth_param
second_key = 16 * 'F'
if (page == 1): # 如果為第一頁
first_param = '{rid:"", offset:"0", total:"true", limit:"20", csrf_token:""}'
h_encText = AES_encrypt(first_param, first_key, iv)#加密方式是第一個參數(shù)和最后一個參數(shù)通過固定iv加密
else:
offset = str((page - 1) * 20)
first_param = '{rid:"", offset:"%s", total:"%s", limit:"20", csrf_token:""}' % (offset, 'false')
h_encText = AES_encrypt(first_param, first_key, iv)
h_encText = AES_encrypt(h_encText, second_key, iv)#第二次加密是上次加密返回值與一個16位的任意字符串加密
return h_encText
# 獲取 encSecKey
def get_encSecKey():
encSecKey = "257348aecb5e556c066de214e531faadd1c55d814f9be95fd06d6bff9f4c7a41f831f6394d5a3fd2e3881736d94a02ca919d952872e7d0a50ebfa1769a7a62d512f5f1ca21aec60bc3819a9c3ffca5eca9a0dba6d6f7249b06f5965ecfff3695b54e1c28f3f624750ed39e7de08fc8493242e26dbc4484a01c76f739e135637c"
return encSecKey
# 解密過程
def AES_encrypt(text, key, iv):
pad = 16 - len(text) % 16
#print(type(text))
text = text + pad * chr(pad)
encryptor = AES.new(key, AES.MODE_CBC, iv)
encrypt_text = encryptor.encrypt(text)
encrypt_text = base64.b64encode(encrypt_text).decode()
return encrypt_text
# 獲得評論json數(shù)據
def get_json(url, params, encSecKey):
data = {
"params": params,
"encSecKey": encSecKey
}
response = requests.post(url, headers=headers, data=data, proxies=proxies)
return response.content
# 抓取某一首歌的全部評論
def get_all_comments(url):
all_comments_list = [] # 存放所有評論
all_comments_list.append(u"用戶ID 用戶昵稱 用戶頭像地址 評論時間 點贊總數(shù) 評論內容\n") # 頭部信息
params = get_params(1)
encSecKey = get_encSecKey()
json_text = get_json(url, params, encSecKey).decode()
json_dict = json.loads(json_text)
comments_num = int(json_dict['total'])
if (comments_num % 20 == 0):
page = int(comments_num / 20)
else:
page = int(comments_num / 20) + 1
print("共有%d頁評論!" % page)
print(type(page))
for i in range(page): # 逐頁抓取
params = get_params(i + 1)
encSecKey = get_encSecKey()
json_text = get_json(url, params, encSecKey).decode()
json_dict = json.loads(json_text)
if i == 0:
print("共有%d條評論!" % comments_num) # 全部評論總數(shù)
for item in json_dict['comments']:
comment = item['content'] # 評論內容
likedCount = item['likedCount'] # 點贊總數(shù)
comment_time = item['time'] # 評論時間(時間戳)
userID = item['user']['userId'] # 評論者id
nickname = item['user']['nickname'] # 昵稱
avatarUrl = item['user']['avatarUrl'] # 頭像地址
comment_info = str(userID) + u" " + nickname + u" " + avatarUrl + u" " + str(
comment_time) + u" " + str(likedCount) + u" " + comment + u"\n"
all_comments_list.append(comment_info)
print("第%d頁抓取完畢!" % (i + 1))
return all_comments_list
# 抓取熱門評論肴茄,返回熱評列表
def get_hot_comments(url):
hot_comments_list = []
hot_comments_list.append("用戶ID " + u"\t" + "用戶昵稱" + u"\t" + "評論時間" + u"\t" + "點贊總數(shù)" + u"\t" + "評論內容" + u"\t" + u"\r\n")
params = get_params(1) # 第一頁
encSecKey = get_encSecKey()
json_text = get_json(url,params,encSecKey).decode()
json_dict = json.loads(json_text)
hot_comments = json_dict['hotComments'] # 熱門評論
#print(hot_comments)
print("共有%d條熱門評論!" % len(hot_comments))
for item in hot_comments:
comment = item['content'] # 評論內容
likedCount = item['likedCount'] # 點贊總數(shù)
#comment_time = item['time'] / 1000 # 評論時間(時間戳)除1000轉化為10位時間戳
#print(comment_time)
# 轉換成localtime
time_local = time.localtime(item['time'] / 1000)
comment_time = time.strftime("%Y-%m-%d", time_local)
userId = item['user']['userId'] # 評論者id
nickname = item['user']['nickname'] # 昵稱
#print(type(comment))
comment_info = str(userId) + u"\t" +nickname+u"\t" +str(comment_time)+u"\t" +str(likedCount) +u"\t\t" + comment + u"\r\n"
hot_comments_list.append(comment_info)
return hot_comments_list
def save_to_file(list, filname):
with codecs.open(filename, 'a', encoding='utf-8') as f:
f.writelines(list)
print("寫入文件成功!")
if __name__ == "__main__":
start_time = time.time()
url = "http://music.163.com/weapi/v1/resource/comments/R_SO_4_185821?csrf_token"
filename = "擱淺.txt"
all_comments_list = get_all_comments(url)
save_to_file(all_comments_list, filename)
#hot_comments = get_hot_comments(url)
#print(hot_comments)
#save_to_file(hot_comments,filename)
end_time = time.time() # 結束時間
print("程序耗時%f秒." % (end_time - start_time))