第03章:爆品监控脚本实战

第03章:爆品监控脚本实战

你的第一个脚本,不需要功能完美,只需要能稳定运行,给客户发出第一份报告。一旦有了第一个付费客户,你才知道下一步要改什么。


这一章,我们从零开始,搭建一个最小可用的"爆品监控"脚本。

目标:

  • 每天抓取TikTok Shop特定类目的热销商品列表
  • 对比前一天的数据,找到排名上升最快的商品(潜在爆品信号)
  • 生成一个Excel报告,发送给客户

这个脚本,你用1-2天可以完成。


环境准备

# 安装依赖
pip install requests pandas openpyxl sqlite3

# (sqlite3是Python内置库,不需要单独安装)

第一步:理解目标数据

在开始写代码之前,先手动操作一次,看看你要抓的数据长什么样。

打开TikTok Shop(shop.tiktok.com 或者TikTok应用),选择一个类目(如"电子产品"),打开浏览器开发者工具(F12)。

在Network选项卡里,过滤fetch/XHR请求,找到返回商品列表的API请求。

你会看到类似这样的JSON结构:

{
  "data": {
    "products": [
      {
        "id": "7xxxxxxxxxx",
        "title": "商品名称",
        "price": {
          "currency": "USD",
          "actual_price": "19.99"
        },
        "sales": 1823,
        "rating": 4.8,
        "review_count": 256
      }
    ]
  }
}

记录下:

  • 请求URL(包含所有参数)
  • 请求Headers(特别是Cookie、x-tt-params等特殊字段)
  • 返回的JSON字段名

第二步:编写爬取脚本

# tiktok_monitor.py

import requests
import json
import sqlite3
import pandas as pd
from datetime import date

# 数据库初始化
def init_db():
    conn = sqlite3.connect("products.db")
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS products (
            id TEXT,
            title TEXT,
            price REAL,
            sales INTEGER,
            rating REAL,
            review_count INTEGER,
            category TEXT,
            date TEXT
        )
    """)
    conn.commit()
    return conn

# 抓取商品数据
def fetch_products(category: str, headers: dict) -> list:
    """
    从TikTok Shop获取指定类目的热销商品。
    URL和参数需要根据实际API调整。
    """
    url = "https://shop.tiktok.com/api/..."  # 替换为实际URL
    params = {
        "category": category,
        "sort_type": "2",  # 按销量排序
        "page": 1,
        "page_size": 100
    }
    
    try:
        response = requests.get(url, params=params, headers=headers, timeout=15)
        response.raise_for_status()
        data = response.json()
        return data.get("data", {}).get("products", [])
    except Exception as e:
        print(f"抓取失败: {e}")
        return []

# 保存到数据库
def save_products(conn, products: list, category: str):
    today = str(date.today())
    cursor = conn.cursor()
    for p in products:
        cursor.execute("""
            INSERT INTO products (id, title, price, sales, rating, review_count, category, date)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            p.get("id"),
            p.get("title"),
            float(p.get("price", {}).get("actual_price", 0)),
            int(p.get("sales", 0)),
            float(p.get("rating", 0)),
            int(p.get("review_count", 0)),
            category,
            today
        ))
    conn.commit()

# 生成报告
def generate_report(conn) -> pd.DataFrame:
    """
    对比今天和昨天的数据,找出销量增幅最大的商品。
    """
    query = """
    SELECT 
        today.id,
        today.title,
        today.category,
        today.price,
        today.sales as sales_today,
        yesterday.sales as sales_yesterday,
        (today.sales - yesterday.sales) as sales_change,
        today.rating
    FROM products today
    LEFT JOIN products yesterday 
        ON today.id = yesterday.id 
        AND yesterday.date = date('now', '-1 day')
    WHERE today.date = date('now')
        AND yesterday.id IS NOT NULL
    ORDER BY sales_change DESC
    LIMIT 50
    """
    df = pd.read_sql_query(query, conn)
    return df

# 导出为Excel
def export_to_excel(df: pd.DataFrame, filename: str = None):
    if filename is None:
        filename = f"爆品监控_{date.today()}.xlsx"
    
    with pd.ExcelWriter(filename, engine='openpyxl') as writer:
        df.to_excel(writer, sheet_name='销量变化排行', index=False)
        
        # 格式化
        worksheet = writer.sheets['销量变化排行']
        for column in worksheet.columns:
            max_length = max(len(str(cell.value)) for cell in column if cell.value)
            worksheet.column_dimensions[column[0].column_letter].width = min(max_length + 2, 50)
    
    print(f"报告已生成: {filename}")
    return filename


# 主函数
if __name__ == "__main__":
    # 配置(从浏览器复制你的请求头)
    HEADERS = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...",
        "Cookie": "YOUR_TIKTOK_COOKIE_HERE",
        "Referer": "https://shop.tiktok.com/"
    }
    
    CATEGORIES = ["electronics", "home", "beauty"]  # 你要监控的类目
    
    conn = init_db()
    
    # 抓取今天的数据
    for category in CATEGORIES:
        print(f"正在抓取类目: {category}")
        products = fetch_products(category, HEADERS)
        save_products(conn, products, category)
        print(f"  保存了 {len(products)} 个商品")
    
    # 生成报告
    df = generate_report(conn)
    if not df.empty:
        export_to_excel(df)
    else:
        print("数据不足,暂无报告(需要至少两天的数据)")
    
    conn.close()

第三步:自动运行

Windows任务计划程序

  1. 打开"任务计划程序"(搜索栏里搜)
  2. 新建任务
  3. 触发器:每天早上7点
  4. 操作:运行 python tiktok_monitor.py(注意指定Python的完整路径)

运行在服务器

如果你想让脚本在服务器上运行(便于给多个客户服务),可以用Linux服务器 + cron:

# 编辑cron任务
crontab -e

# 每天7点运行
0 7 * * * /usr/bin/python3 /home/user/tiktok_monitor.py >> /home/user/monitor.log 2>&1

第四步:发送报告给客户

最简单的方式:把Excel文件通过微信/邮件发送。

自动化发送(Python邮件):

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

def send_email(to_addr: str, file_path: str):
    # 配置你的SMTP服务器(如QQ邮箱)
    smtp_server = "smtp.qq.com"
    smtp_port = 465
    sender_email = "your_email@qq.com"
    sender_password = "YOUR_EMAIL_APP_PASSWORD"  # 使用授权码,不是登录密码
    
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = to_addr
    msg['Subject'] = f"TikTok爆品监控报告 {date.today()}"
    
    # 附件
    with open(file_path, "rb") as f:
        attachment = MIMEBase("application", "octet-stream")
        attachment.set_payload(f.read())
        encoders.encode_base64(attachment)
        attachment.add_header("Content-Disposition", f"attachment; filename={file_path}")
        msg.attach(attachment)
    
    with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, to_addr, msg.as_string())
    
    print(f"报告已发送至 {to_addr}")

脚本的局限性和改进方向

这个基础脚本,有以下不足,可以根据客户需求迭代:

问题 改进方向
Cookie会过期,需要定期更新 研究自动刷新Cookie的方法,或提醒自己手动更新
只有销量排名,没有价格趋势 增加价格字段,用折线图展示价格变化
报告是Excel,不够直观 用Python生成HTML报告,图表更清晰
只监控头部商品,遗漏中腰部爆品 增加监控范围(前500、前1000名)

本章小结

你现在有了一个可以运行的爆品监控脚本框架。

核心要点:

  • 先用浏览器分析网络请求,再写代码
  • 数据存SQLite,方便对比历史
  • 报告发Excel,对客户最友好
  • 先跑通,再迭代

→ 第4章:达人数据雷达的搭建