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

如何显示全部货币列表?修复ECB API汇率输出TypeError问题

问题解答

1. 如何显示全部货币列表?

从ECB汇率数据源中提取完整货币列表,可按以下方式实现:

  • 请求ECB官方汇率XML数据(默认地址为https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml)
  • 解析XML内容,筛选所有包含currency属性的<cube>节点
  • 收集并去重这些节点的currency属性值,即可得到全部货币代码列表

示例代码:

import requests
from bs4 import BeautifulSoup

url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
r = requests.get(url).text
soup = BeautifulSoup(r, "lxml")

# 定位所有带currency属性的cube节点
currency_nodes = soup.find_all("cube", {"currency": True})
# 去重并排序货币代码
currency_list = sorted({node["currency"] for node in currency_nodes})

for currency in currency_list:
    print(currency)

2. 代码错误修复方案

错误原因

原代码中for y in x:的遍历逻辑错误:x是一个<cube>节点,直接遍历会返回节点的子元素或文本内容,而非带有currency和rate属性的目标节点,导致尝试用y['currency']访问字符串索引时触发TypeError: string indices must be integers。

ECB的XML结构层级为:

return (<Cube>
  <Cube time="2024-05-20">
    <Cube currency="USD" rate="1.0789"/>
)
<Cube currency="JPY" rate="161.23"/>
...

正确逻辑是直接定位到最内层带有currency和rate属性的<cube>节点。

修复后的代码

import requests, config
from bs4 import BeautifulSoup

r = requests.get(config.ecb).text
soup = BeautifulSoup(r, "lxml")

# 直接筛选所有带currency和rate属性的cube节点
course = soup.find_all("cube", {"currency": True, "rate": True})
for item in course:
    print(item['currency'], item['rate'])

层级遍历修复方案(保留原循环结构)

若需保留层级遍历逻辑,需添加属性判断,确保仅处理目标节点:

import requests, config
from bs4 import BeautifulSoup

r = requests.get(config.ecb).text
soup = BeautifulSoup(r, "lxml")

course = soup.find_all("cube")
for i in course:
    # 遍历带time属性的第二层cube节点
    for x in i.find_all("cube", {"time": True}):
        # 遍历带currency属性的第三层cube节点
        for y in x.find_all("cube", {"currency": True}):
            print(y['currency'], y['rate'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:25:29