从URL到CSV的XML检索

时间:2019-03-27 11:33:11

标签: python

简而言之,我需要从欧洲中央银行以XML格式检索当前货币和汇率,然后使用python将其转换为CSV文件。它为我创建了一个文件,但未写入所需的正确内容。

XML如下: https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

这是我的代码,但是它不起作用,请帮助大家。

import xml.etree.ElementTree as ET
import requests
import csv

kurzbanky_xml = requests.get("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
root = ET.fromstring(kurzbanky_xml.text)


with open('banka.csv','w',newline='') as Currency_Rate:
    csvwriter = csv.writer(Currency_Rate)
    csvwriter.writerow(['currency','rate'])

    for member in root.iterfind('Cube'):
        cur = cube.attrib['currency']
        rat = cube.attrib['rate']
        csvwriter.writerow([cur,rat])

1 个答案:

答案 0 :(得分:2)

您可以使用xmltodict lib将XML转换为JSON,然后遍历JSON:

import csv
import requests
import xmltodict

r = requests.get("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml").text
data = xmltodict.parse(r)['gesmes:Envelope']['Cube']['Cube']

with open('{}.csv'.format(data['@time']), 'w', newline='') as f:
    csvwriter = csv.writer(f)
    csvwriter.writerow(['currency', 'rate'])

    for cur in data['Cube']:
        csvwriter.writerow([cur['@currency'], cur['@rate']])

输出2019-03-27.csv文件:

currency,rate
USD,1.1261
JPY,124.42
BGN,1.9558
CZK,25.797
DKK,7.4664
GBP,0.85118