×

api开发 电商平台 数据挖掘

开发者指南:利用 1688API 构建商品信息采集系统

admin admin 发表于2025-11-06 17:22:57 浏览106 评论0

抢沙发发表评论

在电商数据分析、竞品监控、供应链管理等场景中,高效采集 1688 平台的商品信息具有重要价值。本文将详细介绍如何利用 1688  API 构建商品信息采集系统,包含完整的开发流程与代码实现。

一、前期准备

1. 注册 1688 平台账号

  • 注册开发者账号

  • 完成认证

  • 获取apiKeyapiSecret

2. 了解核心 API 接口

1688 提供了丰富的商品相关 API,核心接口包括:

  • alibaba.item.search:商品搜索接口

  • alibaba.item.get:获取商品详情

  • alibaba.item.offer.get:获取供应信息详情

  • alibaba.category.get:获取商品类目信息

二、系统架构设计

商品信息采集系统主要包含以下模块:

  • 认证模块:处理 API 调用的签名与权限验证

  • 搜索模块:根据关键词 / 类目筛选商品

  • 详情采集模块:获取商品详细信息

  • 存储模块:将采集的数据持久化

  • 调度模块:控制采集频率与并发量(避免触发限流)

三、代码实现(Python 版)

1. 依赖安装

pip install requests python-dotenv pandas

2. 核心认证模块实现

import time
import hashlib
import hmac
import json
import requests
from dotenv import load_dotenv
import os

# 加载环境变量(建议将敏感信息存入.env文件)
load_dotenv()
APP_KEY = os.getenv("APP_KEY")
APP_SECRET = os.getenv("APP_SECRET")
API_URL = "https://gw.open.1688.com/openapi/param2/2.0/"

class Ali1688Client:
    def __init__(self, app_key, app_secret):
        self.app_key = app_key
        self.app_secret = app_secret
        self.session = requests.Session()

    def _sign(self, params):
        """生成API签名"""
        sorted_params = sorted(params.items(), key=lambda x: x[0])
        sign_str = self.app_secret + ''.join([f"{k}{v}" for k, v in sorted_params]) + self.app_secret
        return hmac.new(
            self.app_secret.encode('utf-8'),
            sign_str.encode('utf-8'),
            hashlib.sha1
        ).hexdigest().upper()

    def call_api(self, api_name, params=None):
        """通用API调用方法"""
        if not params:
            params = {}
            
        # 公共参数
        public_params = {
            "app_key": self.app_key,
            "format": "json",
            "v": "2.0",
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "sign_method": "hmac-sha1"
        }
        
        # 合并参数
        all_params = {**public_params,** params}
        all_params["sign"] = self._sign(all_params)
        
        # 发送请求
        try:
            response = self.session.get(f"{API_URL}{api_name}", params=all_params, timeout=10)
            result = json.loads(response.text)
            if "error_response" in result:
                print(f"API错误: {result['error_response']['msg']}")
                return None
            return result
        except Exception as e:
            print(f"请求异常: {str(e)}")
            return None

3. 商品搜索与详情采集

import pandas as pd
from datetime import datetime

class ProductCollector:
    def __init__(self, client):
        self.client = client
        self.data_path = "product_data"
        os.makedirs(self.data_path, exist_ok=True)

    def search_products(self, keyword, page=1, page_size=40):
        """搜索商品"""
        params = {
            "keywords": keyword,
            "page_no": page,
            "page_size": page_size,
            "sort": "new_desc"  # 按新品排序
        }
        return self.client.call_api("alibaba.item.search", params)

    def get_product_detail(self, product_id):
        """获取商品详情"""
        params = {
            "offer_id": product_id,
            "fields": "offerId,title,picUrl,price,minPrice,maxPrice,"
                      "tradePrice,quantity,categoryId,sellerId,"
                      "province,city,viewCount,saleCount"
        }
        return self.client.call_api("alibaba.item.offer.get", params)

    def batch_collect(self, keyword, total_pages=5):
        """批量采集商品数据"""
        all_products = []
        
        for page in range(1, total_pages + 1):
            print(f"采集第{page}页数据...")
            search_result = self.search_products(keyword, page)
            
            if not search_result or "result" not in search_result:
                continue
                
            for item in search_result["result"]["toReturn"]:
                # 获取商品详情
                detail = self.get_product_detail(item["offerId"])
                if detail and "result" in detail:
                    product_info = detail["result"]
                    all_products.append({
                        "id": product_info.get("offerId"),
                        "title": product_info.get("title"),
                        "price": product_info.get("price"),
                        "min_price": product_info.get("minPrice"),
                        "max_price": product_info.get("maxPrice"),
                        "sale_count": product_info.get("saleCount"),
                        "view_count": product_info.get("viewCount"),
                        "location": f"{product_info.get('province')}-{product_info.get('city')}",
                        "pic_url": product_info.get("picUrl"),
                        "collect_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    })
            
            # 控制请求频率,避免触发限流
            time.sleep(2)
        
        # 保存数据
        df = pd.DataFrame(all_products)
        filename = f"{self.data_path}/{keyword}_{datetime.now().strftime('%Y%m%d')}.csv"
        df.to_csv(filename, index=False, encoding="utf-8-sig")
        print(f"数据采集完成,共{len(all_products)}条,已保存至{filename}")
        return df

4. 系统使用示例

if __name__ == "__main__":
    # 初始化客户端
    client = Ali1688Client(APP_KEY, APP_SECRET)
    
    # 初始化采集器
    collector = ProductCollector(client)
    
    # 批量采集"笔记本电脑"商品数据(5页)
    collector.batch_collect("笔记本电脑", total_pages=5)

四、注意事项

  1. API 调用限制:1688API 有调用频率限制(通常为 100 次 / 分钟),需合理设置请求间隔

  2. 数据合规性:采集的数据需遵守 1688 平台规则,不得用于非法用途

  3. 异常处理:实际开发中需完善重试机制,处理网络波动和 API 临时不可用情况

  4. 反爬策略:避免短时间内大量采集同一类目数据,可分布式部署分散请求源

  5. 权限升级:部分高级接口(如成交数据)需要申请特殊权限

五、扩展方向

  1. 增加代理 IP 池,解决 IP 限流问题

  2. 实现增量采集,只获取新增或变更的商品数据

  3. 开发数据可视化模块,分析商品价格趋势、地域分布等

  4. 集成消息通知,当特定商品价格变动时触发提醒

  5. 对接数据库(如 MySQL、MongoDB),实现大规模数据存储与查询

通过本文介绍的方法,开发者可以快速构建稳定、高效的 1688 商品信息采集系统,为电商运营决策提供数据支持。在实际应用中,需根据业务需求调整采集策略和数据处理逻辑,同时严格遵守平台规范。


少长咸集

群贤毕至

访客