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

Python爬取带动态URL参数的Insee API返回None问题排查

问题根因

返回None, None只会来自两个代码路径:

  • 接口请求返回的状态码不在200~299区间,直接触发前置的返回逻辑
  • try块内的响应解析逻辑抛错,被裸except: pass静默吞掉,最终返回初始化的两个None值

具体触发场景基本是以下三类:

  • 响应结构取值错误:INSEE Sirene V3的siren查询接口,200响应里的uniteLegale是单个JSON对象,不是数组,你写的response.json()['uniteLegale'][0]是对字典按下标0取值,必然触发类型错误,直接进异常分支。
  • 异常被完全吞掉:裸except没有任何日志输出,不管是token过期、网络超时、字段缺失,全被静默跳过,根本定位不到故障点。
  • 鉴权失效:INSEE接口生成的Bearer Token默认有效期只有1小时,token填错、过期、没有对应接口权限,都会返回401/403状态码,直接触发前置的None返回。
修正代码
import requests
import pandas as pd

def extract_siren_code(siren):
    siren_recup, features = None, None
    base_url = "https://api.insee.fr/entreprises/sirene/V3/siren/"
    endpoint = f"{base_url}{siren}"
    # 替换为实际有效的Bearer Token
    headers = {"Authorization": "Bearer <替换为你的有效token>", "Accept": "application/json"}

    response = requests.get(endpoint, headers=headers)
    if response.status_code not in range(200, 299):
        # 打印错误响应方便排查
        print(f"请求失败,状态码:{response.status_code},响应内容:{response.text}")
        return siren_recup, features
    
    try:
        resp_json = response.json()
        # uniteLegale是单个对象,不需要取下标0
        unite_legale_data = resp_json['uniteLegale']
        siren_recup = unite_legale_data['siren']
        features = list(unite_legale_data.keys())
    except Exception as e:
        # 打印具体异常信息,禁止静默吞错
        print(f"解析响应出错:{str(e)},原始响应:{response.text}")

    return siren_recup, features

siren_recup, features = extract_siren_code('824239214')
print(siren_recup, features)
排查要点
  • 运行代码后如果打印的状态码是401/403,直接去INSEE开发者平台重新生成有效token替换即可
  • 如果状态码是200仍解析失败,看打印的异常信息和原始响应,对照实际返回的JSON结构调整字段取值逻辑即可
  • 任何场景下都不要写裸except: pass,异常捕获至少要打印错误信息,否则出问题完全无迹可寻

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 06:09:24