代码

1#!/usr/bin/env python2.7

2 # 头部信息
3 headers = {
4 'Host':"music.163.com",
5 'Accept-Language':"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
6 'Accept-Encoding':"gzip, deflate",
7 'Content-Type':"application/x-www-form-urlencoded",
8 'Cookie':"_ntes_nnid=754361b04b121e078dee797cdb30e0fd,1486026808627; _ntes_nuid=754361b04b121e078dee797cdb30e0fd; JSESSIONID-WYYY=yfqt9ofhY%5CIYNkXW71TqY5OtSZyjE%2FoswGgtl4dMv3Oa7%5CQ50T%2FVaee%2FMSsCifHE0TGtRMYhSPpr20i%5CRO%2BO%2B9pbbJnrUvGzkibhNqw3Tlgn%5Coil%2FrW7zFZZWSA3K9gD77MPSVH6fnv5hIT8ms70MNB3CxK5r3ecj3tFMlWFbFOZmGw%5C%3A1490677541180; iuqxldmzr=32; vjuids=c8ca7976.15a029d006a.0.51373751e63af8; vjlast=1486102528.1490172479.21; _gads=ID=a9eed5e3cae4d252:T=1486102537:S=ALNI_Mb5XX2vlkjsiU5cIy91-ToUDoFxIw; vinfo_n_f_l_n3=411a2def7f75a62e.1.1.1486349441669.1486349607905.1490173828142; [email protected]|1489375076|1|study|00&99|null&null&null#hub&420100#10#0#0|155439&1|study_client|[email protected]; NTES_CMT_USER_INFO=84794134%7Cm155****4439%7Chttps%3A%2F%2Fsimg.ws.126.net%2Fe%2Fimg5.cache.netease.com%2Ftie%2Fimages%2Fyun%2Fphoto_default_62.png.39x39.100.jpg%7Cfalse%7CbTE1NTI3NTk0NDM5QDE2My5jb20%3D; usertrack=c+5+hljHgU0T1FDmA66MAg==; Province=027; City=027; _ga=GA1.2.1549851014.1489469781; _utma=94650624.1549851014.1489469781.1490664577.1490672820.8; __utmc=94650624; __utmz=94650624.1490661822.6.2.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; playerid=81568911; __utmb=94650624.23.10.1490672820",
9 'Connection':"keep-alive",
10 'Referer':'http://music.163.com/'
11 }

33 # 设置代理服务器
34 proxies= {
35 'http:':'http://121.232.146.184',
36 'https:':'https://144.255.48.197'
37 }
38
39 # offset的取值为:(评论页数-1)20,total第一页为true,其余页为false
40 # first_param = '{rid:"", offset:"0", total:"true", limit:"20", csrf_token:""}' # 第一个参数
41 second_param = "010001" # 第二个参数
42 # 第三个参数
43 third_param = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
44 # 第四个参数
45 forth_param = "0CoJUm6Qyw8W8jud"
46
47 # 获取参数
48 def get_params(page): # page为传入页数
49 iv = "0102030405060708"
50 first_key = forth_param
51 second_key = 16 * 'F'
52 if(page == 1): # 如果为第一页
53 first_param = '{rid:"", offset:"0", total:"true", limit:"20", csrf_token:""}'
54 h_encText = AES_encrypt(first_param, first_key, iv)
55 else:
56 offset = str((page-1)
20)
57 first_param = '{rid:"", offset:"%s", total:"%s", limit:"20", csrf_token:""}' %(offset,'false')
58 h_encText = AES_encrypt(first_param, first_key, iv)
59 h_encText = AES_encrypt(h_encText, second_key, iv)
60 return h_encText
61
62 # 获取 encSecKey
63 def get_encSecKey():
64 encSecKey = "257348aecb5e556c066de214e531faadd1c55d814f9be95fd06d6bff9f4c7a41f831f6394d5a3fd2e3881736d94a02ca919d952872e7d0a50ebfa1769a7a62d512f5f1ca21aec60bc3819a9c3ffca5eca9a0dba6d6f7249b06f5965ecfff3695b54e1c28f3f624750ed39e7de08fc8493242e26dbc4484a01c76f739e135637c"
65 return encSecKey
66
67
68 # 解密过程
69 def AES_encrypt(text, key, iv):
70 pad = 16 - len(text) % 16
71 text = text + pad * chr(pad)
72 encryptor = AES.new(key, AES.MODE_CBC, iv)
73 encrypt_text = encryptor.encrypt(text)
74 encrypt_text = base64.b64encode(encrypt_text)
75 return encrypt_text
76
77 # 获得评论json数据
78 def get_json(url, params, encSecKey):
79 data = {
80 "params": params,
81 "encSecKey": encSecKey
82 }
83 response = requests.post(url, headers=headers, data=data,proxies = proxies)
84 return response.content
85
86 # 抓取热门评论,返回热评列表
87 def get_hot_comments(url):
88 hot_comments_list = []
89 hot_comments_list.append(u"用户ID 用户昵称 用户头像地址 评论时间 点赞总数 评论内容\n")
90 params = get_params(1) # 第一页
91 encSecKey = get_encSecKey()
92 json_text = get_json(url,params,encSecKey)
93 json_dict = json.loads(json_text)
94 hot_comments = json_dict['hotComments'] # 热门评论
95 print("共有%d条热门评论!" % len(hot_comments))
96 for item in hot_comments:
97 comment = item['content'] # 评论内容
98 likedCount = item['likedCount'] # 点赞总数
99 comment_time = item['time'] # 评论时间(时间戳)
100 userID = item['user']['userID'] # 评论者id
101 nickname = item['user']['nickname'] # 昵称
102 avatarUrl = item['user']['avatarUrl'] # 头像地址
103 comment_info = userID + " " + nickname + " " + avatarUrl + " " + comment_time + " " + likedCount + " " + comment + u"\n"
104 hot_comments_list.append(comment_info)
105 return hot_comments_list
106
107 # 抓取某一首歌的全部评论
108 def get_all_comments(url):
109 all_comments_list = [] # 存放所有评论
110 all_comments_list.append(u"用户ID 用户昵称 用户头像地址 评论时间 点赞总数 评论内容\n") # 头部信息
111 params = get_params(1)
112 encSecKey = get_encSecKey()
113 json_text = get_json(url,params,encSecKey)
114 json_dict = json.loads(json_text)
115 comments_num = int(json_dict['total'])
116 if(comments_num % 20 == 0):
117 page = comments_num / 20
118 else:
119 page = int(comments_num / 20) + 1
120 print("共有%d页评论!" % page)
121 for i in range(page): # 逐页抓取
122 params = get_params(i+1)
123 encSecKey = get_encSecKey()
124 json_text = get_json(url,params,encSecKey)
125 json_dict = json.loads(json_text)
126 if i == 0:
127 print("共有%d条评论!" % comments_num) # 全部评论总数
128 for item in json_dict['comments']:
129 comment = item['content'] # 评论内容
130 likedCount = item['likedCount'] # 点赞总数
131 comment_time = item['time'] # 评论时间(时间戳)
132 userID = item['user']['userId'] # 评论者id
133 nickname = item['user']['nickname'] # 昵称
134 avatarUrl = item['user']['avatarUrl'] # 头像地址
135 comment_info = unicode(userID) + u" " + nickname + u" " + avatarUrl + u" " + unicode(comment_time) + u" " + unicode(likedCount) + u" " + comment + u"\n"
136 all_comments_list.append(comment_info)
137 print("第%d页抓取完毕!" % (i+1))
138 return all_comments_list
139
140
141 # 将评论写入文本文件
142 def save_to_file(list,filename):
143 with codecs.open(filename,'a',encoding='utf-8') as f:
144 f.writelines(list)
145 print("写入文件成功!")
146
147 if name == "main":
148 start_time = time.time() # 开始时间
149 url = "http://music.163.com/weapi/v1/resource/comments/R_SO_4_186016/?csrf_token="
150 filename = u"晴天.txt"
151 all_comments_list = get_all_comments(url)
152 save_to_file(all_comments_list,filename)
153 end_time = time.time() #结束时间
154 print("程序耗时%f秒." % (end_time - start_time))

你可能感兴趣的:(代码)