ITPub博客

首页 > 大数据 > 数据分析 > 批量获取虾皮商品数据:开放API接口操作详解

批量获取虾皮商品数据:开放API接口操作详解

原创 数据分析 作者:OneLafite 时间:2025-09-12 15:03:30 0 删除 编辑

一、注册与认证:获取API调用权限

  1. 注册开发者账号
    访问虾皮开发者平台,使用企业或个人邮箱完成注册。需提交营业执照(企业开发者)或身份证明(个人开发者)完成实名认证。

  2. 创建应用并获取凭证

    • 在开发者后台创建应用,选择业务场景(如电商导购、数据分析)。
    • 获取 API Key和 Access Token,这是调用接口的关键凭证,需妥善保管。
    • 示例:创建应用后,在“凭证管理”页面可查看API Key,格式为 123456-ABCDE-7890-FGHIJ。

二、接口选择与参数配置:精准获取商品数据

  1. 商品搜索接口(Search Items)
    • 用途:通过关键词批量获取商品列表,支持分页、排序、筛选。

    • 核心参数:

      参数 类型 必填 说明
      keyword String 是 搜索关键词(如“手机”)
      limit Integer 否 每页返回数量(默认20,最大100)
      page Integer 否 页码(从1开始)
      sort_by String 否 排序方式(如 price_asc按价格升序)
    • 示例请求:

      bashGET https://api.shopee.com/api/v2/search_items?keyword=手机&limit=50&page=1&sort_by=price_ascAuthorization: Bearer YOUR_ACCESS_TOKEN
  2. 商品详情接口(Get Product)
    • 用途:获取单个商品的详细信息(如价格、库存、描述)。

    • 核心参数:

      参数 类型 必填 说明
      product_id Integer 是 商品ID(从搜索接口获取)
    • 示例请求:

      bashGET https://api.shopee.com/api/v2/product/get?product_id=123456789Authorization: Bearer YOUR_ACCESS_TOKEN

三、签名生成与请求发送:确保调用安全

  1. 签名算法(HMAC-SHA256)
    • 按字典序拼接参数(如 keyword=手机&limit=50),生成待签名字符串。
    • 使用API Key作为密钥,通过HMAC-SHA256算法生成签名。
    • Python示例:
      pythonimport hmacimport hashlibimport base64def generate_signature(params, api_key):message = "&".join([f"{k}={v}" for k, v in sorted(params.items())])signature = hmac.new(api_key.encode(), message.encode(), hashlib.sha256).digest()return base64.b64encode(signature).decode()params = {"keyword": "手机", "limit": 50}signature = generate_signature(params, "YOUR_API_KEY")
  2. 发送HTTP请求
    • 使用 requests库发送GET请求,携带签名和授权头。
    • 完整示例:
      pythonimport requestsdef search_items(keyword, limit=50, page=1):url = "https://api.shopee.com/api/v2/search_items"params = {"keyword": keyword,"limit": limit,"page": page,"timestamp": int(time.time())}headers = {"Authorization": f"Bearer YOUR_ACCESS_TOKEN","X-Shopee-Signature": generate_signature(params, "YOUR_API_KEY")}response = requests.get(url, params=params, headers=headers)return response.json()result = search_items("手机")print(result["items"][0]["name"])  # 输出第一个商品名称

四、数据处理与存储:高效利用数据

  1. JSON解析与清洗
    • 使用 json模块解析API返回的JSON数据,提取关键字段(如商品ID、名称、价格)。
    • 示例:
      pythonimport jsondata = '{"items": [{"product_id": 123, "name": "手机", "price": 1999}]}'parsed_data = json.loads(data)for item in parsed_data["items"]:print(f"商品ID: {item['product_id']}, 名称: {item['name']}, 价格: {item['price']}")
  2. 存储方案选择
    • 数据库:MySQL(结构化数据)或MongoDB(非结构化数据)。
    • 文件存储:CSV(适合小规模数据)或Parquet(适合大规模数据分析)。
    • 示例(存储到CSV):
      pythonimport csvwith open("products.csv", "w", newline="", encoding="utf-8") as f:writer = csv.writer(f)writer.writerow(["商品ID", "名称", "价格"])for item in parsed_data["items"]:writer.writerow([item["product_id"], item["name"], item["price"]])

五、高频场景与代码示例:快速落地应用

  1. 电商导购网站
    • 需求:展示虾皮平台上的热门商品和优惠信息。
    • 实现:调用搜索接口获取高销量商品,结合详情接口获取价格和库存。
    • 代码片段:
      pythondef get_hot_products(category_id, limit=10):params = {"category_id": category_id,"limit": limit,"sort_by": "sales"}response = search_items("", **params)  # 假设search_items支持额外参数return [item["name"] for item in response["items"]]hot_phones = get_hot_products(100)  # 获取手机类目热销商品
  2. 价格比较工具
    • 需求:对比虾皮与其他平台的商品价格。
    • 实现:调用虾皮API获取价格,结合其他平台API或爬虫数据。
    • 代码片段:
      pythondef compare_prices(product_name):shopee_data = search_items(product_name)shopee_price = shopee_data["items"][0]["price"]# 假设调用其他平台API获取价格other_platform_price = 1899  return {"shopee": shopee_price, "other_platform": other_platform_price}price_diff = compare_prices("iPhone 13")

六、注意事项:规避风险,确保稳定

  1. API调用限制
    • 虾皮API对调用频率有限制(如每分钟100次),需通过缓存或异步队列控制请求速率。
    • 示例(使用Redis缓存):
      pythonimport redisr = redis.Redis(host="localhost", port=6379)def cached_search(keyword):cache_key = f"shopee_search:{keyword}"cached_data = r.get(cache_key)if cached_data:return json.loads(cached_data)data = search_items(keyword)r.setex(cache_key, 3600, json.dumps(data))  # 缓存1小时return data
  2. 错误处理与重试
    • 捕获网络异常和API错误(如429表示频率限制),实现自动重试。
    • 示例:
      pythonimport timefrom requests.exceptions import RequestExceptiondef safe_api_call(url, params, headers, max_retries=3):for i in range(max_retries):try:response = requests.get(url, params=params, headers=headers)response.raise_for_status()return response.json()except RequestException as e:if i == max_retries - 1:raisetime.sleep(2 ** i)  # 指数退避
  3. 合规性要求
    • 遵守虾皮平台规则,禁止爬取非公开数据或进行恶意刷、单。
    • 定期检查API文档更新(如接口地址、参数变更),避免兼容性问题。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70046834/viewspace-3095599/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
专业研发电商平台API开放接口,搭建独立站系统,反向海淘代购系统十年+,https://o0b.cn/lafite。

注册时间:2025-06-20

  • 博文量
    231
  • 访问量
    258448