def get_product_data(product_id): """ 通过product_id获取含有商品信息的html/json,从中获取good_id、brand、price数据生成数据字典 :param product_id: (str) 商品ID :return: (dict) 商品基本信息的数据字典 """ try: product_url = PRODUCT_URL.format(product_id) mylogger.debug("获取商品基本信息页面URL -- {}".format(product_url)) product_html = get_page_html(product_url) good_id = (re.findall('>货号:(.*?)</li>', product_html, re.S))[0] brand = (re.findall("id=\"parameter-brand.*?title=\'(.*?)\'>品牌", product_html, re.S))[0] price_url = PRICE_URL.format(product_id) json_data = get_json_data(price_url) price = json_data['p'] product_data = {"good_id": good_id, "brand": brand, "price": price} mylogger.debug("获取商品基本信息字典 -- {}".format(product_data)) return product_data except IndexError: mylogger.error("商品基本信息空缺,跳过 -- {}".format(product_id)) return None
def get_comment_data(product_id, score, page, product): """ 获取product_id相应score和page的评论数据,与商品基本信息一起构成数据字典返回 :param product_id: (str) 商品ID :param score: (int) 商品评分 :param page: (int) 评论页数 :param product: (dict) 商品基本信息的数据字典 :return: (dict) 商品信息及评论数据字典 """ comment_url = COMMENT_URL.format(product_id, score, page) mylogger.debug("获取商品评论页面URL -- {}".format(comment_url)) json_data = get_json_data(comment_url) data = json_data['comments'] comment_data = [] for i in range(len(data)): comment = { "good_id": product['good_id'], "brand": product['brand'], "price": product['price'], "creationTime": data[i]['creationTime'], "score": data[i]['score'], "comment": data[i]['content'] } comment_data.append(comment) mylogger.debug("获取商品评论数据 -- counts:{}".format(len(comment_data))) return comment_data
def get_comment_num(product_id): """ 通过product_id获取含有商品评论的信息json,从中获取最大评论数 :param product_id: (str) 商品ID :return: (int) 最大评论数量 """ comment_url = COMMENT_URL.format(product_id, '1', '0') mylogger.debug("获取商品评论页面URL:{}".format(comment_url)) json_data = get_json_data(comment_url) comment_num = json_data['productCommentSummary']['commentCount'] mylogger.debug("获取商品总评论数 -- number:{}".format(comment_num)) return comment_num