价格比较工具可帮助购物者和经销商在多家零售商中找到最优惠的价格。构建一个平台需要查询多个平台、规范价格格式并按价值对结果进行排名。 Scavio API 通过统一端点覆盖亚马逊和沃尔玛,从而可以轻松查询两个平台并并排比较结果。本教程构建了一个比较函数,该函数接受产品名称、并行查询两个平台并返回排序的报价列表。
前置条件
- Python 3.10 或更高版本
- requests 和并发.futures (stdlib) 可用
- Scavio API 密钥
- 对异步或并发编程的基本了解
操作指南
步骤 1: 同时查询两个平台
使用concurrent.futures.ThreadPoolExecutor同时查询Amazon和Walmart,减少总延迟。
from concurrent.futures import ThreadPoolExecutor, as_completed
def search_platform(platform: str, query: str) -> list[dict]:
r = requests.post(
"https://api.scavio.dev/api/v1/search",
headers={"x-api-key": API_KEY},
json={"platform": platform, "query": query, "marketplace": "US"}
)
r.raise_for_status()
return r.json().get("products", [])
def fetch_both(query: str) -> dict:
with ThreadPoolExecutor(max_workers=2) as ex:
futures = {ex.submit(search_platform, p, query): p for p in ["amazon", "walmart"]}
return {futures[f]: f.result() for f in as_completed(futures)}步骤 2: 跨平台价格标准化
两个平台都以字符串形式返回价格,例如“$29.99”。将它们解析为浮点数以进行比较。
def normalize(product: dict, source: str) -> dict:
price_str = product.get("price", "")
price = float(price_str.replace("$", "").replace(",", "")) if price_str else None
return {"source": source, "title": product.get("title"), "price": price, "raw": price_str}步骤 3: 合并和排序结果
将两个平台的结果合并到一个列表中,并按价格升序排序。
def compare(query: str) -> list[dict]:
results = fetch_both(query)
items = []
for source, products in results.items():
items.extend(normalize(p, source) for p in products[:5])
return sorted(items, key=lambda x: x["price"] or float("inf"))步骤 4: 显示比较表
打印格式化表格,显示两个平台上产品的最佳价格。
offers = compare("Sony WH-1000XM5")
print(f"{'Source':<10} {'Price':<10} {'Title'}")
for o in offers[:6]:
print(f"{o['source']:<10} {o['raw']:<10} {o['title'][:50]}")Python 示例
import os
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
API_KEY = os.environ.get("SCAVIO_API_KEY", "your_scavio_api_key")
ENDPOINT = "https://api.scavio.dev/api/v1/search"
def search(platform: str, query: str) -> list[dict]:
r = requests.post(ENDPOINT, headers={"x-api-key": API_KEY},
json={"platform": platform, "query": query, "marketplace": "US"})
r.raise_for_status()
return r.json().get("products", [])
def compare(query: str) -> list[dict]:
with ThreadPoolExecutor(max_workers=2) as ex:
futs = {ex.submit(search, p, query): p for p in ["amazon", "walmart"]}
all_items = []
for f in as_completed(futs):
src = futs[f]
for p in f.result()[:5]:
price_str = p.get("price", "")
price = float(price_str.replace("$", "").replace(",", "")) if price_str else None
all_items.append({"source": src, "price": price, "raw": price_str, "title": p.get("title", "")})
return sorted(all_items, key=lambda x: x["price"] or float("inf"))
if __name__ == "__main__":
for o in compare("Sony WH-1000XM5")[:6]:
print(f"{o['source']:<10} {o['raw']:<10} {o['title'][:50]}")JavaScript 示例
const API_KEY = process.env.SCAVIO_API_KEY || "your_scavio_api_key";
const ENDPOINT = "https://api.scavio.dev/api/v1/search";
async function searchPlatform(platform, query) {
const res = await fetch(ENDPOINT, {
method: "POST",
headers: { "x-api-key": API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ platform, query, marketplace: "US" })
});
const data = await res.json();
return (data.products || []).slice(0, 5).map(p => ({ source: platform, ...p }));
}
async function compare(query) {
const [amazon, walmart] = await Promise.all([
searchPlatform("amazon", query),
searchPlatform("walmart", query)
]);
const all = [...amazon, ...walmart];
return all.sort((a, b) => {
const pa = parseFloat((a.price || "").replace(/[$,]/g, "")) || Infinity;
const pb = parseFloat((b.price || "").replace(/[$,]/g, "")) || Infinity;
return pa - pb;
});
}
compare("Sony WH-1000XM5").then(results => {
results.slice(0, 6).forEach(r => console.log(`${r.source}: ${r.price} — ${r.title?.slice(0, 50)}`));
}).catch(console.error);预期输出
amazon $279.00 Sony WH-1000XM5 Wireless Noise Canceling Headphones
amazon $289.99 Sony WH-1000XM5 Wireless Headphones (Midnight Black)
walmart $279.00 Sony WH1000XM5 Bluetooth Headphones
walmart $299.00 Sony WH-1000XM5 Premium Wireless Headphones