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

Python中如何根据请求返回值跳过脚本?解决空列表变量未定义错误

问题分析

当API返回的resources为空列表时,for label in resources循环不会执行,taxon_id变量从未被赋值,后续代码直接引用它就会触发"local variable referenced before assignment"错误。

解决方案

根据你的需求,有两种常见处理方式:

方式1:提前初始化变量,避免未定义

如果只需要处理最后一个taxon_id,先初始化taxon_id为None,后续判断是否有有效值再执行请求:

taxon_url = f"https://records-ws.nbnatlas.org/occurrences/search?q=data_resource_uid:{uid}&fq=taxon_concept_lsid:*&facets=taxon_concept_lsid&pageSize=0&flimit=-1"
taxon_response = requests.get(taxon_url)
json_response = taxon_response.json()

jsonpath_expr = parse('$..facetResults[*].fieldResult[*]')
resources = [ match.value for match in jsonpath_expr.find(json_response) ]

taxon_id = None  # 提前初始化变量
for label in resources:
    taxon_id = label['label']
    print(taxon_id)

# 只有当taxon_id有值时才执行后续请求
if taxon_id is not None:
    class_url = f"https://species-ws.nbnatlas.org/species/{taxon_id}"
    class_response = requests.get(class_url)
    class_json = class_response.json()
else:
    print(f"未找到uid为{uid}的taxon_id")

方式2:将后续请求放入循环,处理所有taxon_id

如果需要处理每个提取到的taxon_id,把后续请求逻辑放到循环内部,同时处理空列表的情况:

taxon_url = f"https://records-ws.nbnatlas.org/occurrences/search?q=data_resource_uid:{uid}&fq=taxon_concept_lsid:*&facets=taxon_concept_lsid&pageSize=0&flimit=-1"
taxon_response = requests.get(taxon_url)
json_response = taxon_response.json()

jsonpath_expr = parse('$..facetResults[*].fieldResult[*]')
resources = [ match.value for match in jsonpath_expr.find(json_response) ]

if not resources:
    print(f"uid为{uid}的请求返回空列表,无taxon_id可处理")
else:
    for label in resources:
        taxon_id = label['label']
        print(taxon_id)
        # 处理当前taxon_id的请求
        class_url = f"https://species-ws.nbnatlas.org/species/{taxon_id}"
        class_response = requests.get(class_url)
        class_json = class_response.json()
        # 这里添加对class_json的业务处理逻辑

额外建议

  • 可以添加API请求的状态码检查,比如if taxon_response.status_code == 200,避免因请求失败导致的JSON解析错误。
  • 如果resources为空是异常情况,可以抛出自定义异常终止流程,而非仅打印提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:45:32