def get_comments_from_maoyan(self, offset): comments = [] json_str = self.get_one_page_comment_json_from_maoyan(offset) if json_str is None: return None try: data1 = json_str['cmts'] # 获取评论内容 data2 = json_str['hcmts'] # 获取评论内容 data = data1 + data2 except KeyError: return None for item in data: comment = Comment(self.movie) # 使用get方法获取值,避免出现KeyError comment.user_loc = item.get('cityName') comment.user_avatar = item.get('avatarurl') comment.user_name = item.get('nickName') comment.user_id = item.get('userId') comment.comment = item.get('content') comment.create_time = item.get('time') comment.vote_count = item.get('approve') comments.append(comment) return comments
def decode_json(self, json_str): # 创建评论变量 comments = [] # 解析关键的根节点 count = json_str['count'] start = json_str['start'] interests = json_str['interests'] total = json_str['total'] # print('本次获取的个数为:', count) # print('评论为:', interests) # print('起始评论数为:', start) # print('总评论数为:', total) # 解析所需要的评论内容 for interest in interests: comment = Comment(self.movie) user = interest['user'] rating = interest['rating'] loc = user['loc'] if loc is not None: loc_name = loc['name'] comment.user_loc = loc_name comment.user_avatar = user['avatar'] comment.user_name = user['name'] comment.user_id = user['id'] if rating is not None: comment.rate = rating['value'] comment.comment = interest['comment'] comment.create_time = interest['create_time'] comment.vote_count = interest['vote_count'] comments.append(comment) # 保存评论内容到文件中 self.save_comments(comments, 0) return start, len(interests), total