
下面给你最简单、直接可用、程序员一看就懂的版本:
如何用 Python 实现淘宝商品详情 API 返回数据的准确性校验
不绕弯、不废话,直接落地。
通过这些校验,保证你的业务不崩溃、不错误、不脏数据。
python
运行
def check_taobao_item_accuracy(json_data):
"""
淘宝商品详情API数据准确性校验
返回:True=校验通过, False=不通过, msg=错误信息
"""
try:
# 1. 判断API返回是否成功
if "item_get_response" not in json_data:
return False, "返回结构异常,无 item_get_response"
item = json_data["item_get_response"].get("item", {})
if not item:
return False, "未获取到商品数据"
# 2. 商品ID校验(必须存在、是数字)
num_iid = item.get("num_iid")
if not num_iid or not str(num_iid).isdigit():
return False, f"商品ID无效:{num_iid}"
# 3. 标题校验(不能为空)
title = item.get("title")
if not title or len(title) < 5:
return False, "商品标题过短或为空"
# 4. 价格校验(必须 > 0)
price = item.get("price", "0")
try:
price_val = float(price)
if price_val <= 0:
return False, f"价格异常:{price}"
except:
return False, f"价格格式错误:{price}"
# 5. 库存校验(不能为负)
num = item.get("num", 0)
try:
stock_val = int(num)
if stock_val < 0:
return False, f"库存不能为负数:{num}"
except:
return False, f"库存格式错误:{num}"
# 6. 主图校验(必须有图片)
pic_url = item.get("pic_url")
if not pic_url or "http" not in pic_url:
return False, "商品主图无效"
# 7. 类目校验(必须有类目)
cid = item.get("cid")
if not cid:
return False, "商品类目cid不存在"
# 全部通过
return True, "数据校验通过,准确有效"
except Exception as e:
return False, f"校验异常:{str(e)}"python
运行
# 假设这是你调用淘宝API返回的json数据
json_result = requests.get(api_url, params=params).json()
# 校验
is_ok, msg = check_taobao_item_accuracy(json_result)
print(is_ok, msg)这些都是导致程序崩溃、数据分析错误、上货失败的元凶!
json
{
"item_get_response": {
"item": {
"num_iid": "680012345678",
"title": "2025夏季新款纯棉T恤",
"price": "59.00",
"num": 200,
"pic_url": "https://img.taobao.com/xxx.jpg",
"cid": 50015261,
"detail_url": "https://detail.tmall.com/..."
}
}
}Python 校验淘宝 API 商品数据 = 字段非空 + 格式正确 + 数值合法
确保你的数据分析、商品搬家、ERP 对接100% 稳定不出错。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。