
1. 项目背景与核心价值电商比价工具已经成为现代消费者购物决策的必备助手。作为国内最大的两个电商平台京东和淘宝的商品价格差异经常能达到10%-20%特别是3C数码、家电等高单价商品。传统人工比价方式效率极低而通过API接口实现自动化比价可以快速获取全网最优价格。这个项目最实用的地方在于直接调用官方API接口数据准确可靠支持关键词搜索和商品匹配自动识别同款商品实时比较到手价含优惠券、满减等输出结构化比价结果可直接用于决策注意调用电商平台API需要先申请开发者权限淘宝开放平台和京东开放平台都有免费的基础调用额度个人开发者完全够用。2. 环境准备与API申请2.1 开发环境配置推荐使用Python 3.8环境主要依赖库pip install requests python-dotenv建议项目结构/price-comparison ├── .env # 存储API密钥 ├── api/ │ ├── jd.py # 京东接口封装 │ └── taobao.py # 淘宝接口封装 ├── core.py # 比价核心逻辑 └── main.py # 入口文件2.2 API密钥申请步骤淘宝开放平台访问开放平台官网注册开发者账号创建应用选择网站应用类型获取App Key和App Secret设置IP白名单建议使用服务器固定IP京东宙斯平台注册京东联盟账号申请API权限需要实名认证获取access_token注意调用频率限制默认500次/天实操技巧将API密钥存储在环境变量中不要硬编码在代码里。使用python-dotenv管理敏感信息。3. 核心接口实现详解3.1 淘宝商品搜索接口淘宝API采用REST风格需要签名验证。关键参数包括q搜索关键词page_no分页页码fields指定返回字段签名生成算法def generate_sign(params, app_secret): 淘宝API签名算法 sorted_params sorted(params.items()) sign_str app_secret .join(f{k}{v} for k,v in sorted_params) app_secret return hashlib.md5(sign_str.encode()).hexdigest().upper()典型响应结构{ items: [ { num_iid: 商品ID, title: 商品标题, price: 当前价, original_price: 原价, coupon_price: 券后价 } ] }3.2 京东商品搜索接口京东API采用POST请求需要额外timestamp参数。关键区别使用method参数指定API方法需要传参access_token分页参数为page/pageSize价格处理特别注意# 京东价格需要除以100单位是分 real_price float(item[price]) / 1003.3 比价核心算法实现商品匹配是比价的关键难点我们采用多维度相似度计算标题相似度使用difflib库品牌关键词提取规格参数比对如手机的内存、颜色图片特征匹配可选def match_products(item1, item2): 商品匹配算法 # 标题相似度 title_score SequenceMatcher(None, item1[title], item2[title]).ratio() # 品牌识别 brand_match 1 if extract_brand(item1) extract_brand(item2) else 0 # 综合评分 return title_score * 0.6 brand_match * 0.44. 完整可运行代码实现4.1 淘宝API封装类import hashlib import requests from urllib.parse import urlencode class TaobaoAPI: def __init__(self, app_key, app_secret): self.app_key app_key self.app_secret app_secret self.base_url https://eco.taobao.com/router/rest def search_items(self, keyword, page1, page_size20): params { method: taobao.item.search, app_key: self.app_key, q: keyword, page_no: page, page_size: page_size, timestamp: datetime.now().strftime(%Y-%m-%d %H:%M:%S), format: json, v: 2.0, sign_method: md5, fields: num_iid,title,price,pic_url,coupon_price } params[sign] self._generate_sign(params) response requests.get(self.base_url, paramsparams) return self._parse_response(response.json()) def _generate_sign(self, params): # 签名生成实现 pass def _parse_response(self, response): # 响应解析实现 pass4.2 京东API封装类class JdAPI: def __init__(self, app_key, app_secret, access_token): self.app_key app_key self.app_secret app_secret self.access_token access_token self.base_url https://api.jd.com/routerjson def search_items(self, keyword, page1, page_size20): params { method: jingdong.ware.search, app_key: self.app_key, access_token: self.access_token, timestamp: datetime.now().strftime(%Y-%m-%d %H:%M:%S), format: json, v: 2.0, sign_method: md5, keyword: keyword, page: page, pageSize: page_size } params[sign] self._generate_sign(params) response requests.post(self.base_url, dataparams) return self._parse_response(response.json())4.3 比价服务整合class PriceComparator: def __init__(self, taobao_api, jd_api): self.taobao taobao_api self.jd jd_api def compare(self, keyword, top_n5): # 获取淘宝结果 tb_results self.taobao.search_items(keyword)[items] # 获取京东结果 jd_results self.jd.search_items(keyword)[items] # 商品匹配与比价 comparisons [] for tb_item in tb_results[:top_n]: best_match None best_score 0 for jd_item in jd_results: score self._calculate_similarity(tb_item, jd_item) if score best_score: best_score score best_match jd_item if best_match and best_score 0.7: comparisons.append({ taobao: tb_item, jd: best_match, price_diff: float(tb_item[price]) - float(best_match[price]), similarity: best_score }) return sorted(comparisons, keylambda x: abs(x[price_diff]), reverseTrue)5. 实战技巧与避坑指南5.1 高频问题解决方案Q1API返回Invalid signature错误检查时间戳格式必须是YYYY-MM-DD HH:MM:SS确认参数排序严格按照字母顺序验证app_secret是否正确Q2商品匹配准确率低增加品牌识别逻辑建立品牌关键词库使用商品分类ID辅助匹配引入图片相似度比对需OCR支持Q3请求被限流添加随机延迟0.5-2秒 between requests使用代理IP池轮询遵守平台QPS限制淘宝默认5QPS5.2 性能优化建议异步请求改造import aiohttp async def fetch_concurrently(apis): async with aiohttp.ClientSession() as session: tasks [api.fetch(session) for api in apis] return await asyncio.gather(*tasks)缓存策略使用Redis缓存API响应设置15-30分钟过期对高频搜索词预取数据实现本地文件缓存兜底结果预处理提前计算好价格差异百分比标记历史最低价商品过滤无效商品如预售、缺货5.3 商业化应用扩展对于想商业化的开发者可以考虑增加浏览器插件形态开发微信小程序版本提供价格监控API服务添加商品收藏比价功能结合 affiliate 链接实现流量变现重要提示商业化应用需要特别注意各平台的API使用政策避免违规。京东要求月调用量超过10万次需要签订商务合同。