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

Discogs爬虫遇AttributeError:num_for_sale空值处理问题

问题分析与解决方案

错误原因

你仅判断了'lowest_price'是否存在于market_data中,但忽略了核心情况:当release无在售商品时,API返回的lowest_price是null(对应Python中的None)。此时market_data['lowest_price']拿到的是None,而None对象没有get()方法,直接调用就会触发AttributeError。

代码改写示例

安全的核心逻辑实现

以下是修正后的代码,彻底解决None值处理问题:

# 从release数据中获取marketplace信息,用空字典替代None,避免后续访问报错
market_data = release.get('marketplace', {})

# 安全获取num_for_sale:API返回null时默认设为0,方便筛选条件判断
num_for_sale = market_data.get('num_for_sale', 0)

# 执行三重筛选条件
if num_have <= 18 and num_versions <= 2 and num_for_sale <= 5:
    # 链式get方法处理lowest_price:
    # 1. 先取lowest_price,不存在或为None时返回空字典
    # 2. 再从空字典中取value,不存在时返回None
    value = market_data.get('lowest_price', {}).get('value', None)

关键改进点

  • 用release.get('marketplace', {})确保market_data始终是字典类型,避免因marketplace为None导致后续调用get()报错。
  • 用market_data.get('num_for_sale', 0)将API返回的null转换为0,让num_for_sale <=5的筛选条件能正确覆盖无在售商品的情况。
  • 链式调用get()方法:即使lowest_price是None,也会用空字典兜底,不会触发AttributeError。

备选:异常捕获方案

如果你更倾向于用异常处理的方式,也可以把value的获取逻辑包在try块中:

if num_have <= 18 and num_versions <= 2 and num_for_sale <= 5:
    try:
        value = market_data['lowest_price'].get('value', None)
    except (KeyError, AttributeError):
        # 捕获lowest_price不存在或为None的情况
        value = None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 23:15:34