Python调用API查询汇率:人民币美元换算与批量计算
讲解用Python requests调用公开汇率API,获取实时汇率并批量计算人民币对美元、欧元等多币种换算结果,适合外贸、财务报表自动化。
场景痛点
做外贸、跨境电商、财务对账经常要换算汇率,打开搜索引擎一个个查太慢,手动填到Excel里又怕数据过期。调用公开汇率API,传入基准币种和目标币种,拿到实时汇率,再批量换算一堆金额,结果直接导出CSV,比手动查准多了。
用到的库
pip install requests beautifulsoup4 lxml
完整代码
# 导入库
import csv
import requests
def get_exchange_rate(base="CNY", target="USD"):
"""获取 base -> target 的实时汇率"""
# 示例:用公开汇率接口,实际可换成 exchangerate-api 等
# URL格式类似:https://api.example.com/latest?base=CNY
url = "https://httpbin.org/json"
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
data = resp.json()
# 假设返回结构:
# {
# "base": "CNY",
# "rates": {"USD": 0.14, "EUR": 0.13, "JPY": 21.5}
# }
rates = data.get("rates", {})
rate = rates.get(target)
if rate is None:
print(f"未找到 {target} 的汇率")
return None
print(f"1 {base} = {rate} {target}")
return rate
except requests.exceptions.RequestException as e:
print("汇率接口请求失败:", e)
return None
def batch_convert(amounts, base="CNY", target="USD"):
"""批量换算金额列表"""
rate = get_exchange_rate(base, target)
if rate is None:
return []
results = []
for amount in amounts:
converted = round(amount * rate, 2)
results.append({
"原始金额": amount,
"币种": base,
"兑换后": converted,
"目标币种": target,
})
print(f"{amount} {base} = {converted} {target}")
return results
def save_csv(rows, filename="exchange.csv"):
with open(filename, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=["原始金额", "币种", "兑换后", "目标币种"])
writer.writeheader()
writer.writerows(rows)
print(f"已保存 {len(rows)} 条到 {filename}")
if __name__ == "__main__":
# 一批需要换算的金额,实际项目里可能从Excel读
amounts = [100, 500, 1000, 5000, 10000]
rows = batch_convert(amounts, base="CNY", target="USD")
if rows:
save_csv(rows)
代码讲解
get_exchange_rate调用汇率API,返回一个浮点数汇率。真实API返回结构通常是{base: 基准货币, rates: {币种: 汇率}}。- 用字典
.get()安全取值,目标币种不存在时返回None而不是崩溃。 batch_convert拿到汇率后批量乘一遍,每笔金额保留两位小数,符合财务习惯。- 结果存成CSV,四列:原始金额、币种、兑换后、目标币种,直接Excel打开就能用。
- 如果要同时换算多个目标币种(美元、欧元、日元),循环调用
get_exchange_rate即可。
运行结果
运行后先打印汇率,再逐行打印每笔金额换算结果,当前目录生成 exchange.csv。示例用httpbin返回占位数据,换成真实API后会得到实际汇率。
注意事项
- 汇率API很多免费版只支持USD作为基准,CNY转其他币种要先转USD再转过去。
- 汇率实时波动,财务对账时要记录查询时间,不能拿今天的汇率算上个月的账。
- 免费接口有调用上限,建议一天查一次汇率缓存到本地,换算时直接读缓存。
- 涉及实际金额计算时注意浮点精度,财务场景用
decimal.Decimal更稳妥。

更新时间:2026-09-14 20:52:56
上一篇:Python调用公开API获取天气数据:实时查询与解析