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

Anaconda/JupyterLab中fredapi.get_series()报AttributeError问题求助

问题分析与解决

问题描述

在Anaconda/JupyterLab环境中使用fredapi 0.4.2拉取数据时,调用get_series()函数出现AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'getchildren'错误,但相同代码在DataCamp云端笔记本可正常运行。

尝试的代码:

import fredapi as Fred
my_api_key='some_number'
fred=Fred(api_key=my_api_key)
sp500=fred.get_series('SP500')  # 注:原代码笔误为fred_get_series,已修正

错误信息:

AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15588\3735180914.py in <module>
      1 fred = Fred(api_key='48687714d90448d876bb115d06578128')
----> 2 fred.get_series('SP500')

~\anaconda3\envs\my_models\lib\site-packages\fredapi\fred.py in get_series(self, series_id, observation_start, observation_end, **kwargs)
    133             raise ValueError('No data exists for series id: ' + series_id)
    134         data = {}
---> 135         for child in root.getchildren():
    136             val = child.get('value')
    137             if val == self.nan_char:

AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'getchildren'

原因

  • Python 3.9及以上版本中,xml.etree.ElementTree.Element的getchildren()方法被官方移除,替换为直接迭代元素本身(即for child in root:)。
  • 本地Anaconda环境的Python版本≥3.9,而DataCamp云端使用的是Python 3.8及以下版本(仍支持getchildren()),同时使用的fredapi 0.4.2是旧版本,代码未适配高版本Python的API变更。

解决方案

方案1:升级fredapi到最新版本

新版本的fredapi已修复此兼容性问题,执行以下命令升级:

pip install --upgrade fredapi
# 或使用conda安装(若用conda管理环境)
conda install -c conda-forge fredapi --upgrade

方案2:手动修改fredapi源码(仅临时应急)

找到报错提示中的fred.py文件(路径:~\anaconda3\envs\my_models\lib\site-packages\fredapi\fred.py),定位到第135行,将:

for child in root.getchildren():

修改为:

for child in root:

保存文件后,重启JupyterLab内核即可。

额外修正

原代码中有笔误:fred_get_series('SP500')应改为fred.get_series('SP500'),虽然本次报错并非由此导致,但需修正避免后续问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:27:21