eBay 按 item_id 批量查询商品:一次 40 个,按 40 次计费

发布于 2026年10月29日

看到 items-batch 一次能塞 40 个 item_id,多数人心里先记一笔账:一次请求,一次扣费。这笔账是错的。接口自己在 meta 里写了答案:发出 2 个 ID,requested 是 2,upstream_calls 也是 2,billing_note 写着 priced per item id, not per call。40 个 ID 一次发出,账上就是 40 笔,和你循环调 40 次 item-detail 一样。批量换来的是并发,不是折扣。下面先用计数器验证,再把名单分给两条价格不同的通道,最后给出一个带预算上限的脚本。

一次 40 个 item_id,仍是 40 次页面抓取

eBay 没有批量取商品详情的端点,所以 items-batch 对名单里的每个 ID 各做一次独立查询,相当于一次页面抓取,并发执行后合并返回;探测里 meta.concurrency 是 8。每个 ID 返回的记录与 item-detail 相同:price、list_price、condition、brand、mpn、item_specifics、卖家信誉、运费、退货政策、quantity_sold、watchers,拍卖商品还有 current_bid 和 bids(这两个文档里有,探测没有覆盖)。

所以“批量查询是不是更省请求”的答案很直接:不省。省不下来的钱有三类:名单里的重复 ID,已经下架的 ID,以及只需要一个价格却取回整条记录的 ID。后面几节就是处理这三类。

这个问题常见的背景是 eBay 官方的多商品查询要么已停用,要么要申请受限权限。这里不需要 eBay 开发者账号和 OAuth 令牌,也不用解析 HTML,只需要平台密钥。

放大批量前,先对比 meta.requested 与 meta.upstream_calls

先用 2 个 ID 跑一次,把计数器看明白。登录后在控制台复制平台密钥,替换下面的 YOUR_API_KEY。请求不需要 eBay 登录、Cookie 或上一步的结果;打开本页、复制命令都不会发出查询,只有你自己执行才会按 ID 扣点数。这是 POST 加 JSON 请求体,两个 ID 和 com 站点是探测时用过的输入,不代表推荐商品。

curl --request POST \
  'https://api.opendata-api.com/api/project/ebay/items-batch?key=YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{"item_ids":"287070621317,301782776848","domain":"com"}'

响应分三层读。HTTP 200 只说明传输完成;网关响应带 code、message、data,code 不是 200 就是业务失败;data 里才是操作结果,它自己还有 ok、meta、data。探测的结果是:ok 为 true,requested 2,upstream_calls 2,record_count 2,latency_ms 约 3800,data.not_found 是空数组,data.unavailable 是 null。

放大之前把两条规则写进代码:requested 必须等于你发出的个数;每次响应的 upstream_calls 累加进自己的账本,而不是用“发了几次请求”估算。密钥在查询参数里,日志、截图、工单和异常信息都可能把它带出去,后面的脚本不打印异常原文,原因就在这里。

卡片通道:用 search 的 (id1,id2,…) 一次查 6 个

只想知道价格、标题和成色,有一条更便宜的路:把 search 的 query 写成 (id1,id2,id3),这是 eBay 自己的 OR 写法,直接按已知 ID 返回列表卡片。按接口说明,一次搜索算一笔查询,实测约 6 个 ID 一组,第 7 个会被丢掉。卡片只有 item_id、title、price、condition、shipping、image、url,没有 item_specifics、卖家和退货政策。

{"query": "(287070621317,301782776848)", "domain": "com"}

同样 6 个 ID,卡片通道 1 笔,完整记录通道 6 笔。但这条通道的行为来自接口说明,我们的探测没有跑过,上线前先拿 6 个已知 ID 试一次,核对返回的 item_id。还有一个陷阱:search 没有 not_found 数组,卡片里缺了某个 ID,可能是下架,也可能是被丢掉,只能记作“没拿到卡片”,不能直接当成下架。

哪些 ID 值得拉完整记录

价格巡检的名单里,多数 ID 今天和昨天没有区别。让卡片先过一遍,只有两类升级到完整记录:价格相对上次记录变动超过阈值(脚本默认 5%)的,以及没拿到卡片的,后者交给 items-batch 的 not_found 给出权威答复。要看 item_specifics、卖家信誉,或者拍卖的 current_bid、bids,就走完整通道。

名单 200 个 ID,账是这样算的:

做法查询数
全部走 items-batch200
卡片优先,20 个升级34 + 20 = 54
卡片优先,166 个升级34 + 166 = 200,持平
卡片优先,200 个全升级34 + 200 = 234

34 是 200 除以 6 向上取整。升级数一旦达到 N 减去 ⌈N/6⌉,卡片优先就没有优势。所以首次入库、要给每个 ID 补全属性的一次性任务,直接走完整通道;每晚的价格巡检才适合卡片优先。

名单从哪来:自己的表格,或者 seller-items 翻页取出的某个卖家全部在售商品,或者 deals 的特价列表(带原价);要把类目名称换成数字 ID,用 categories。同一份名单固定一个 domain,币种和本地站点都跟着它走。

按 40 切片,并把 not_found 与请求失败分开记账

切片大小有两个说法:接口概览写每次最多 40 个,item_ids 的参数说明写最多 15 个,探测只发过 2 个。所以脚本里 FULL_CHUNK 是常量,默认取较严的 15;想用 40,先拿一批真实 ID 跑一次,确认 meta.requested 等于你发出的个数,再改。切得越大,单次耗时越长,按 8 路并发推算,40 个要好几轮,超时别设太短,脚本用 120 秒。

每一批的结果归入四个互不混淆的桶:

  • data.items 里的记录:拿到了,写入结果。
  • data.not_found:接口明确答复这些 ID 已结束、被移除或无效。它们仍然计入 upstream_calls,所以别让下架的 ID 每晚重发一次,确认后从名单里剔除。
  • 请求失败:HTTP 非 200、code 非 200、ok 不是 true,或者超时。这只说明没有得到答复,不能写成“已下架”。失败的那一批可能已经计费,超时尤其如此,脚本一律按已花费记账,也不会自动重发。
  • 两边都不见的 ID:既不在 items 也不在 not_found,单独列出。data.unavailable 在探测里是 null,文档没有解释它的含义,脚本遇到非空值就原样保存,不去猜。

省下的是等待时间,不是请求数

接口自己的实测:8 个 ID 顺序调用 item-detail 要 25.6 秒,一次 items-batch 只要 4.1 秒,约 6.2 倍;探测里 2 个 ID 的 latency_ms 约 3800。扣费完全一样,所以批量是延迟优化,不是成本优化。用户在页面上点“刷新这 8 个”,批量值得;凌晨跑的任务,快慢无所谓,要降成本只有缩名单:去重、剔除 not_found、走卡片通道。另外每个响应带 meta.fetched_at,价格是抓取那一刻的在售价,不是成交价,价格历史要自己存。

带预算上限的批量脚本

脚本的输入是一份 CSV,两列 item_id,last_price,用 --cap 限定本次最多计费多少笔:卡片通道一次算 1 笔,完整记录一个 ID 算 1 笔。发出任何请求之前先算计划,名单去重后卡片通道需要 ⌈N/6⌉ 笔,连这一步都放不下就直接退出。随后卡片先行,变动最大的 ID 排在前面升级;预算快用完时最后一批会缩小,放不下的写进 deferred 留给下一轮。结果写入 ebay_budget_report.json,密钥只从环境变量 OPENDATA_API_KEY 读取。

#!/usr/bin/env python3
"""Refresh an eBay watchlist under a hard cap on billed lookups."""
import argparse
import csv
import json
import math
import os
import sys

import requests

BASE = "https://api.opendata-api.com/api/project/ebay"
CARD_CHUNK = 6    # search "(id1,...)" returns about 6 cards per call
FULL_CHUNK = 15   # stricter documented figure; raise toward 40 only after verifying meta.requested


class Budget:
    def __init__(self, cap):
        self.cap, self.spent = cap, 0

    @property
    def room(self):
        return self.cap - self.spent

    def spend(self, n):
        self.spent += n  # an ambiguous failure (timeout) stays counted as spent

    def settle(self, sent, reported):
        if isinstance(reported, int):  # trust the counter the API reports
            self.spent += reported - sent


def call(operation, body):
    try:
        resp = requests.post(f"{BASE}/{operation}", params={"key": os.environ["OPENDATA_API_KEY"]},
                             json=body, timeout=120)
        reply = resp.json()
    except (requests.RequestException, ValueError) as exc:
        # Never print the exception text: it can contain the full URL with the key.
        raise RuntimeError(type(exc).__name__) from None
    if resp.status_code != 200 or str(reply.get("code")) != "200":
        raise RuntimeError(f"HTTP {resp.status_code} / code {reply.get('code')}")
    result = reply.get("data")
    if not isinstance(result, dict) or result.get("ok") is not True:
        raise RuntimeError("operation ok is not true")
    return result


def chunks(seq, size):
    for i in range(0, len(seq), size):
        yield seq[i:i + size]


def card_lane(last, domain, budget, failed):
    cards = {}
    for chunk in chunks(list(last), CARD_CHUNK):
        budget.spend(1)  # the plan check guarantees the card lane fits the cap
        try:
            result = call("search", {"query": "(" + ",".join(chunk) + ")", "domain": domain,
                                     "max_results": CARD_CHUNK})
        except RuntimeError as exc:
            failed.append({"lane": "card", "ids": chunk, "reason": str(exc)})
            continue
        for card in (result.get("data") or {}).get("results") or []:
            cards[str(card.get("item_id"))] = card
    return cards


def full_lane(ids, domain, budget, report):
    pos = 0
    while pos < len(ids) and budget.room > 0:
        chunk = ids[pos:pos + min(FULL_CHUNK, budget.room)]  # the last chunk shrinks to fit the cap
        budget.spend(len(chunk))
        pos += len(chunk)
        try:
            result = call("items-batch", {"item_ids": ",".join(chunk), "domain": domain})
        except RuntimeError as exc:
            report["failed"].append({"lane": "full", "ids": chunk, "reason": str(exc)})
            continue
        meta, data = result.get("meta") or {}, result.get("data") or {}
        budget.settle(len(chunk), meta.get("upstream_calls"))
        if meta.get("requested") != len(chunk):
            print(f"warning: sent {len(chunk)} ids but meta.requested={meta.get('requested')}")
        found = {str(it.get("item_id")): it for it in data.get("items") or []}
        gone = [str(i) for i in data.get("not_found") or []]
        report["records"].update(found)
        report["not_found"].extend(gone)
        report["unanswered"].extend(i for i in chunk if i not in found and i not in gone)
        if data.get("unavailable"):
            report["unavailable"].append(data["unavailable"])  # meaning undocumented: record as is
    report["deferred"] = ids[pos:]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("watchlist", help="CSV with columns item_id,last_price")
    ap.add_argument("--cap", type=int, required=True, help="max billed lookups for this run")
    ap.add_argument("--domain", default="com")
    ap.add_argument("--threshold", type=float, default=0.05, help="price move that earns a full record")
    args = ap.parse_args()
    if not os.environ.get("OPENDATA_API_KEY"):
        sys.exit("set OPENDATA_API_KEY first")

    with open(args.watchlist, newline="", encoding="utf-8") as fh:
        last = {r["item_id"].strip(): float(r["last_price"]) for r in csv.DictReader(fh)}
    card_calls = math.ceil(len(last) / CARD_CHUNK)
    print(f"{len(last)} unique ids: {card_calls} card lookups, at most {len(last)} full lookups, cap {args.cap}")
    if card_calls > args.cap:
        sys.exit("cap is too small even for the card lane; nothing was sent")

    budget = Budget(args.cap)
    report = {"records": {}, "not_found": [], "unanswered": [], "unavailable": [], "failed": [], "deferred": []}
    cards = card_lane(last, args.domain, budget, report["failed"])

    card_failed = {i for f in report["failed"] for i in f["ids"]}  # unanswered, not "missing"
    moved, missing = [], []
    for item_id, old in last.items():
        card = cards.get(item_id)
        if item_id in card_failed:
            continue
        if card is None:
            missing.append(item_id)  # no card is not proof of removal: let items-batch answer
            continue
        try:
            change = abs(float(card["price"]["value"]) - old) / old
        except (KeyError, TypeError, ValueError, ZeroDivisionError):
            change = 1.0  # unreadable price: spend a full record rather than guess
        if change >= args.threshold:
            moved.append((change, item_id))
    shortlist = [i for _, i in sorted(moved, reverse=True)] + missing  # biggest movers first

    full_lane(shortlist, args.domain, budget, report)
    report["budget"] = {"cap": args.cap, "spent": budget.spent}
    with open("ebay_budget_report.json", "w", encoding="utf-8") as fh:
        json.dump(report, fh, ensure_ascii=False, indent=2)
    print(f"spent {budget.spent}/{args.cap}; full records {len(report['records'])}, "
          f"not_found {len(report['not_found'])}, failed chunks {len(report['failed'])}, "
          f"deferred {len(report['deferred'])}")


if __name__ == "__main__":
    main()
read -s OPENDATA_API_KEY && export OPENDATA_API_KEY
python ebay_budget.py watchlist.csv --cap 80 --domain com

跑完先看 budget.spent 是否和预期一致,再看 failed 与 deferred:前者和控制台里的用量对一下,后者留给下一轮。