天猫评论爬取和处理

从天猫捞取评论数据,存储到MySql数据库,进而处理MySql中的数据,筛选需要的数据,钉钉发送给对应的人。

Python爬取数据

  • URL拼接(得到请求的URL)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    paras = urllib.urlencode({'itemId' : itemId,
    'order' : order,
    'pageSize' : pageSize,
    'currentPage' : currentPage,
    'sellerId' : 1,
    'append' : 0,
    'content' : 0,
    'tagId' : '',
    'callback' : 'jsonp618'})
    commentUrl = tmall_url + paras
  • 加载数据(网络请求,读取数据)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # 类调用
    spider = Spider()
    data = spider.load_data(commentUrl)
    ...
    def load_data(self,url):
    user_agent="Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10"
    headers = {"User-Agent": user_agent}
    req = urllib2.Request(url, headers = headers)
    response = urllib2.urlopen(req)
    html = response.read()
    return html
  • 处理数据(加载到的数据根据需要进行处理)

    1
    2
    3
    4
    # 去除换行并转码
    proStr = data.replace('\n','').replace('\r','').decode('latin-1')
    # 转为Json对象
    jsonData = json.loads(proStr[9:-1])
  • 写入MySql数据库

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    def data_to_mysql(self,data):
    conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test',port=3306)
    cursor = conn.cursor()
    for item in data:
    if "wap" in item["attributesMap"]:
    wap = item["attributesMap"]["wap"]
    else:
    wap = ""
    if "ttid" in item["attributesMap"]:
    ttid = item["attributesMap"]["ttid"]
    else:
    ttid = ""
    #print item
    print "\n"
    print item["id"]
    if cursor.execute("select * from jxl_comment where id = %s",[item["id"]]) <= 0:
    strPics = ""
    if len(item["pics"]) > 0:
    for itemPic in item["pics"]:
    strPics = strPics + itemPic + ","
    print cursor.execute('insert into jxl_comment (id,attributes,wap,ttid,pic_height,leafCatId,pic_width,tmall_vip_level,spuId,sku,enableTime,auctionSku,cmsSource,displayUserNick,gmtCreateTime,pics,rateContent,rateDate,sellerId,tmallSweetPic,tradeEndTime,send_status) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
    [item["id"],item["attributes"],wap,ttid,item["attributesMap"]["pic_height"],
    item["attributesMap"]["leafCatId"],item["attributesMap"]["pic_width"],item["attributesMap"]["tmall_vip_level"],item["attributesMap"]["spuId"],item["attributesMap"]["sku"],
    item["attributesMap"]["enableTime"],item["auctionSku"],item["cmsSource"],item["displayUserNick"],item["gmtCreateTime"],
    strPics,item["rateContent"],item["rateDate"],item["sellerId"],item["tmallSweetPic"],
    item["tradeEndTime"],0])
    conn.commit()
    cursor.close()
    conn.close()

Python程序,1分钟的间隔去读取新的评论

  • Linux注册服务

    • Python程序实现1分钟间隔

      1
      2
      3
      4
      def main():
      while True:
      ProcessData('21416908877',1,20,1)
      time.sleep(60)
    • Python程序文件上传到Linux服务器
      我上传的路径为:/var/www/Flask/tmall.py

    • Linux中/etc/rc.d/init.d/目录下创建一个服务脚本

      1
      2
      3
      4
      5
      6
      7
      touch tmall
      vim tmall
      //写入以下内容
      @author:root
      chkconfig:35 85 15
      description:this tmall comment service
      !/usr/bin/env python /var/www/Flask/tmall.py
    • 添加服务到系统

      1
      chkconfig –add tmall
    • 查看服务运行状态

      1
      chkconfig –list tmall

      运行后此服务一直不能起作用(未找到原因)???

  • Linux运行一个后台程序

    • 创建后台运行程序

      1
      nohup python /var/www/Flask/tmall.py &
    • 成功后按任意键,回车退出

    • 使用exit()退出终端界面,否则进程也跟着被杀死

      1
      exit

      测试运行有效,在我用putty再次登陆Root账号,运行进程被kill了,未找到原因???

      window服务处理程序

      此处只列出逻辑代码,具体细节请查看代码。。。

    • 遍历MySql未处理的程序

      1
      2
      3
      4
      5
      6
      7
      8
      connection.ConnectionString = connStr.ConnectionString;
      string sqlQuery = @"select * from jxl_comment where send_status = 0";
      var listComment = connection.Query(sqlQuery);
      foreach (var item in listComment)
      {
      //业务处理
      }
    • 写入语义差评率和处理状态

      1
      2
      3
      4
      5
      string strContent = EncodeHelper.LatinToDefaul(item.rateContent);
      int iBadRate = DataProcess(SemanticProcess(JsonConvert.SerializeObject(strContent)));
      string sqlUp = string.Format("update jxl_comment set send_status = 1,bad_rate = {1} where id = {0}", item.id,iBadRate);
      connection.Execute(sqlUp);
    • 钉钉数据处理

      1
      2
      3
      4
      5
      string strComment = CommentProcess(strContent,item.pics,iBadRate);
      if (!string.IsNullOrEmpty(strComment))
      {
      SendCommentToDing(strComment);
      }

注册windows服务

  • 生成解决方案
    解决方案debug/bin目录下,生成exe应用程序
  • 部署注册服务
    命令行下:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe 解决方案下的exe服务应用程序
    如,命令行:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe D:\WindowServer\aTestServer.exe
  • 启动服务
    计算机->管理->服务 找到对应服务启动即可
  • 卸载服务
    C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u 解决方案下的exe服务应用程序