要獲取匯率數據,可以使用Python中的第三方庫進行網絡請求并解析數據。以下是一個使用requests和json庫獲取匯率數據的示例代碼:
import requests
import json
# 設置API endpoint
url = "https://api.exchangerate-api.com/v4/latest/USD"
# 發起GET請求
response = requests.get(url)
# 檢查響應狀態碼
if response.status_code == 200:
data = response.json()
# 打印所有匯率
rates = data['rates']
for currency, rate in rates.items():
print(f"{currency}: {rate}")
else:
print("Failed to fetch exchange rates")
在上面的示例中,我們使用requests庫發送GET請求到一個匯率API的endpoint,并解析返回的JSON數據。您可以根據需要修改代碼來獲取不同貨幣對的匯率數據。