实战:利用淘宝API实现商品评论数据实时抓取

71 阅读3分钟

一、准备工作

  1. 注册****开发者****账号

  2. 创建应用获取关键凭证:

    • api_key - 应用唯一标识
    • api_secret - 应用安全密钥
  3. 申请"商品评论"API权限(需企业资质)


二、核心代码实现

import requests
import time
import hashlib
import json
from datetime import datetime

class TaobaoCommentAPI:
    def __init__(self, app_key, app_secret):
        self.app_key = app_key
        self.app_secret = app_secret
        self.api_url = "https://eco.taobao.com/router/rest"
        
    def _generate_sign(self, params):
        """生成API签名"""
        param_str = ''.join([f"{k}{params[k]}" for k in sorted(params)])
        sign_str = self.app_secret + param_str + self.app_secret
        return hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper()
    
    def get_comments(self, item_id, page=1, page_size=20):
        """获取商品评论数据"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 构造基础参数
        params = {
            "app_key": self.app_key,
            "method": "taobao.item.comments.get",
            "timestamp": timestamp,
            "format": "json",
            "v": "2.0",
            "sign_method": "md5",
            "num_iid": str(item_id),
            "page_no": str(page),
            "page_size": str(page_size),
            "fields": "tid,content,created,score,nick"
        }
        
        # 生成签名并添加
        params["sign"] = self._generate_sign(params)
        
        try:
            response = requests.get(self.api_url, params=params)
            result = response.json()
            
            if 'error_response' in result:
                print(f"API错误: {result['error_response']['msg']}")
                return None
                
            return result['item_comments_get_response']['comments']
            
        except Exception as e:
            print(f"请求异常: {str(e)}")
            return None

class RealTimeMonitor:
    def __init__(self, api, item_id, interval=60):
        self.api = api
        self.item_id = item_id
        self.interval = interval
        self.last_fetch_time = int(time.time())
    
    def start_monitoring(self):
        """启动实时监控"""
        print(f"开始监控商品 {self.item_id} 的评论...")
        while True:
            current_time = int(time.time())
            print(f"\n[{datetime.now()}] 获取新评论...")
            
            # 获取最新评论(实际开发中应使用增量时间戳参数)
            comments = self.api.get_comments(self.item_id, page_size=50)
            
            if comments and 'comment' in comments:
                self.process_comments(comments['comment'])
            
            time.sleep(self.interval)
    
    def process_comments(self, comments):
        """处理并存储评论数据"""
        for comment in comments:
            # 此处添加实际业务处理逻辑
            print(f"新评论 [{comment['nick']}]: {comment['content'][:30]}...")
            # 存储到数据库或文件(示例保存到JSON)
            with open(f"comments_{self.item_id}.json", "a") as f:
                f.write(json.dumps(comment, ensure_ascii=False) + "\n")

# 使用示例
if __name__ == "__main__":
    # 配置您的凭证
    APP_KEY = "您的APP_KEY"
    APP_SECRET = "您的APP_SECRET"
    ITEM_ID = "627986654321"  # 示例商品ID
    
    api = TaobaoCommentAPI(APP_KEY, APP_SECRET)
    monitor = RealTimeMonitor(api, ITEM_ID, interval=300)  # 每5分钟抓取一次
    monitor.start_monitoring()

 

三、关键技术解析

  1. 签名机制

    • 使用MD5加密生成请求签名
    • 参数排序+双重app_secret拼接
    • 保障API请求的安全性
  2. 实时监控设计

    • 定时轮询机制(生产环境建议使用Webhook)
    • 增量获取(示例简化,实际需记录最后获取时间)
    • 错误重试机制(代码中未展示,需添加)
  3. 数据存储优化

# MongoDB存储示例
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client['taobao']
collection = db['comments']

# 替换文件存储为
collection.insert_one(comment)

 

四、注意事项

  1. 频率限制

    • 免费版:单应用500次/天
    • 高级版:最高10万次/天(需购买)
  2. 数据字段说明

    字段名说明类型
    tid评论IDstring
    content评论内容string
    created创建时间date
    score评分(1-5)int
    nick用户昵称string
  3. 避坑指南

    • 企业认证才能获取完整评论数据
    • 特殊字符需URL编码处理
    • 使用try-except处理网络波动
    • 重要操作添加日志记录

五、扩展优化建议

  1. 分布式采集
# Celery分布式任务示例
from celery import Celery

app = Celery('taobao')
@app.task
def fetch_comments(item_id):
    api.get_comments(item_id)

 

  1. 数据清洗管道

    • 去除广告评论
    • 情感分析(使用SnowNLP库)
    • 关键词提取
  2. 可视化展示

# 使用Pyecharts生成词云
from pyecharts.charts import WordCloud

wordcloud = WordCloud().add("", keyword_data, word_size_range=[20, 100])
wordcloud.render("comment_analysis.html")

 重要提示:实际使用时请替换示例中的商品ID和认证信息,并根据淘宝API最新文档调整参数。