200-Study | Python学习 | 爬虫项目 | JD商品评论 | 小牛电动车-02

项目背景

一开始从京东上获取用户的反馈是想分析用户对某店铺产品的看法:是否满意?对哪一方面满意?对哪一方面不满意?
后来是Roger提出了销量预测的需要,但是由于数据量不充分而且线上的销售量仅占全体销售量5%的水平;所以不考虑使用评论数据来进行销量分析。

京东评论URL分析

通过页面分析工具抓取向服务器申请评论的请求头的信息:
https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv14894&productId=100001364160&score=0&sortType=5&page=1&pageSize=10&isShadowSku=0&rid=0&fold=1
对这个请求而言,有比较多个参数。

  • url = ‘https://sclub.jd.com/comment/productPageComments.action’
  • callback = ‘fetchJSON_comment98vv14894’
  • productId = ‘100001364160’
  • score = ‘0’
  • sortType = ‘5’
  • page = ‘1’
  • pageSize = ‘10’
  • isShadowSku = ‘0’
  • rid = ‘0’
  • fold = ‘1’
    这里的socre选项对应0,1,2,3分别表示全部评价,差评和中评和好评。
    sortTyep选项对应5,6分别表示推荐排序和时间排序
    如果不考虑反爬虫的技术,如果是对评论进行抓取;只要使用requests发送对应的请求然后从对应的json里面获取到信息。

环境要求

  • python 3.x
  • requests, json, pandas

准备工作

  • 产品编码列表

代码结构

  • url列表
  • get_html
  • get_comment 获取一页的评论
  1. get_html

def get_html(url,data):
   # 得到网页源代码
   try:
       r = requests.get(url,params = data)
       r.raise_for_status()
       r.encoding = r.apparent_encoding
       return r.text
   except:
       print('网页html获取失败')
  1. get_comment
def get_comment(html):
    #获得一页的评论
    commentList=[]
    i = json.dumps(html)  # 将页面内容编码成json数据,(无论什么格式的数据编码后都变成了字符串类型str)
    j = json.loads(i)  # 解码,将json数据解码为Python对象
    comment = re.findall(r'{"productAttr":.*}', j)  # 对网页内容筛选找到我们想要的数据,得到值为字典的字符串即'{a:1,b:2}'
    #print(comment)
    comm_dict = json.loads(comment[0])  # 将json对象obj解码为对应的字典dict
    commentSummary = comm_dict['comments']  # 得到包含评论的字典组成的列表
    SKU_id = comm_dict['productCommentSummary']['skuId']
    for comment in commentSummary:  # 遍历每个包含评论的字典,获得评论和打分
        c_content = ''.join(comment['content'].split())  # 获得评论,由于有的评论有换行,这里用split()去空格,换行,并用join()连接起来形成一整段评论,便于存储
        score = comment['score']  # 用户打分
        time = comment['creationTime']
        nickname = comment['nickname']
        product_name = comment['referenceName']
        user_level = comment['userLevelName']
        reply_cnt = comment['replyCount']
        view_cnt = comment['viewCount']      commentList.append([nickname,time,product_name,c_content,score,user_level,reply_cnt,view_cnt,SKU_id])
    return commentList
def conments(url,comment_ct,pro_id):
    #url主体和爬取网页的数量
    data = {'callback': 'fetchJSON_comment98vv329',  # 调整页数page
            'productId': pro_id,
            'score': 0,
            'sortType': 6,
            'page': 0,
            'pageSize': 10,
            'isShadowSku': 0,
            'rid': 0,
            'fold': 1
            }


    comments=list()
    if comment_ct <= 10:
        num = 1
    else:
        num = comment_ct//10
    for i in range(num+1):
        try:    #跳过失败页面
            data['page']=i
            html = get_html(url, data)
            comment = get_comment(html)
        except:
            continue
        comments+=comment
        print('页数',i)
        time.sleep(3)#由于网站反爬虫,所以每爬一页停3秒
    return comments


  1. 主程序
import requests
import json
import pandas as pd
import time
time_start = time.time()
url = 'https://sclub.jd.com/comment/productPageComments.action?'
SKU_info = pd.read_csv('C:/Users/Think/Desktop/data_niu/jd_item_info_2019_03_11.csv',engine = 'python',encoding = 'utf16',sep='\t')
comm = list()
for pro_id,comment_ct in zip(SKU_info['Product ID'],SKU_info.comment_ct):
    comm += conments(url,comment_ct,str(pro_id))
    name=['nickname','time','product_name','c_content','score','user_level','reply_cnt','view_cnt','SKU_id']
    file=pd.DataFrame(columns=name,data=comm)
    file.to_csv('C:/Users/Think/Desktop/data_niu/jd_comment_request.csv',encoding = 'utf_16',index=False,sep = '\t')
    print(str(pro_id) + '--------Done-------')
    
print('共计%d条评论'%(len(comm)))#打印出总共多少条评论
#name=['nickname','time','product_name','c_content','score','user_level','reply_cnt','view_cnt','SKU_id']
#file=pd.DataFrame(columns=name,data=comm)
#file.to_csv('C:/Users/Think/Desktop/data_niu/jd_comment_request.csv',index=False)
time_end = time.time()
print('耗时%s秒' % (time_end - time_start))

---------------------------------------------2019-09-08----------------------------------------------------
后续这种方法好像是不能用了。可以考虑慢慢地用selenium爬取或者重新进行一下网页分析。

你可能感兴趣的:(pandas)