You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

爬取JSON字段时误获amountUsdCents,如何正确提取amount值?

问题

我有两个名称相近的JSON字段,爬取数据时总是获取到amountUsdCents的值,但实际只需要amount字段的值。JSON示例如下:

[{"sizeOption":{"presentation":"3.5","value":3.5},"shoeCondition":"new_no_defects","boxCondition":"good_condition","lowestPriceCents":{"currency":"GBP","amount":25764,"amountUsdCents":31294},"instantShipLowestPriceCents":{"currency":"GBP","amount":34686,"amountUsdCents":42051},"lastSoldPriceCents":{"currency":"GBP","amount":18200,"amountUsdCents":22000},"stockStatus":"single_in_stock"},{"sizeOption":...}]

使用的Python代码片段(仅关注price_cents赋值部分):

for entry in output:
    if (entry['shoeCondition'] == "new_no_defects") and (entry['boxCondition'] == "good_condition"):
        size = entry['sizeOption']['presentation']
        try:
            price_cents = entry['lastSoldPriceCents']['amount']
        except KeyError:
            price_cents = 'OOS!'
        results.append((size, price_cents))

预期获取到18200,但实际得到22000,求解决思路。

解决思路
  • 验证数据源结构:直接打印entry['lastSoldPriceCents']的完整字典内容,确认amount和amountUsdCents的键值对是否和你预期的一致,排查是否是数据源返回的字段值本身颠倒。
  • 检查键名拼写:确认代码中'amount'的拼写完全正确,包括大小写、字符长度,避免因键名错误意外取到其他字段。
  • 排查后续代码干扰:检查是否有其他逻辑修改了results列表中的值,比如后续步骤把price_cents替换成了amountUsdCents的内容。
  • 添加调试输出:在price_cents赋值后立刻打印该变量,同时打印对应的entry['lastSoldPriceCents'],对比两者是否匹配,定位问题出在赋值环节还是后续处理。
  • 强制类型转换(可选):如果数据源返回的字段类型异常,可尝试转换类型后赋值,比如price_cents = int(entry['lastSoldPriceCents']['amount']),确保拿到正确数值。

内容的提问来源于stack exchange,提问作者user21495274

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:25:12