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

如何通过USDA API获取全部水果营养数据并导出至Excel?

解决USDA API获取完整水果营养数据的问题

USDA FDC Search API默认每页返回50条结果,要获取完整数据,需通过分页参数循环请求所有页面,具体实现如下:

核心修改思路

  • 利用API的pageSize(每页条数,最大可设为1000)和pageNumber(页码,从1开始递增)参数实现分页查询
  • 循环请求直到没有新数据返回,统一收集所有结果后再导出Excel

修改后的完整代码

import requests
import pandas as pd

def call_api(food_name, api_key, page_size=1000, page_number=1):
    url = (f'https://api.nal.usda.gov/fdc/v1/foods/search?api_key={api_key}'
           f'&query={food_name}&pageSize={page_size}&pageNumber={page_number}')
    response = requests.get(url)
    response.raise_for_status()  # 捕获API请求异常
    return response.json()

# 替换为你的API密钥
API_KEY = "你的API密钥"
# 可优化关键词,比如改为"fruit raw"仅获取生水果数据
FOOD_QUERY = "raw"

table_data = []
page_num = 1

while True:
    api_response = call_api(FOOD_QUERY, API_KEY, page_number=page_num)
    foods = api_response.get('foods', [])
    
    if not foods:
        break  # 无更多数据,终止循环
    
    # 处理当前页的食物营养数据
    for food_item in foods:
        row = {"Description": food_item["description"]}
        for nutrient in food_item["foodNutrients"]:
            nutrient_name = nutrient["nutrientName"]
            row[nutrient_name] = nutrient["value"]
        table_data.append(row)
    
    print(f"已获取第 {page_num} 页,共 {len(foods)} 条数据")
    page_num += 1

# 导出完整数据到Excel
df = pd.DataFrame(table_data)
print(f"总数据条数:{len(df)}")
df.to_excel('full_fruit_nutrients.xlsx', index=False)

关键说明

  • 分页效率优化:将pageSize设为1000(API允许的最大值),可减少请求次数,提升获取数据的效率
  • 循环终止逻辑:当某一页返回的foods为空列表时,判定所有数据已获取完成
  • 关键词精准度:如果仅需要水果数据,建议将FOOD_QUERY改为"fruit raw",过滤非水果类食材
  • 错误排查:response.raise_for_status()会在API请求失败时抛出异常,方便定位网络或权限问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:40:59