简体   繁体   English

从URL请求XML文件并使用python另存为CSV

[英]Request XML file from URL and save as CSV using python

I am new in python coding and I would like to get XML file from a server, parse it and save to csv file. 我是python编码的新手,我想从服务器获取XML文件,将其解析并保存为csv文件。

2 parts are ok, I am able to get the file and parse it, but there is an issue with saving as a csv. 2个部分都可以,我可以获取文件并对其进行解析,但是另存为csv存在问题。

The code: 编码:

import requests
import numpy as np

hu = requests.get('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml', stream=True)
from xml.etree import ElementTree as ET
tree = ET.parse(hu.raw)
root = tree.getroot()
namespaces = {'ex': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'}
for cube in root.findall('.//ex:Cube[@currency]', namespaces=namespaces):
    np.savetxt('data.csv', (cube.attrib['currency'], cube.attrib['rate']), delimiter=',')   

Error I get is: mismatch between array dtype and format specifier. 我得到的错误是:数组dtype和格式说明符之间不匹配。 It probably means I get data and try to save it as array, and there appears a mismatch. 这可能意味着我获取了数据并尝试将其保存为数组,并且出现了不匹配的情况。 But i am not sure how to fix the problem and to not have a mismatch. 但是我不确定如何解决该问题以及是否不匹配。

Thank you 谢谢

from the docs , your second argument in np.savetext should be a tuple of equal sized arrays . 文档中 ,您在np.savetext的第二个参数应该是大小相等的数组tuple What you are providing are strings: 您提供的是字符串:

>>> x = y = z = np.arange(0.0,5.0,1.0)
>>> np.savetxt('test.out', x, delimiter=',')   # X is an array
>>> np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
>>> np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation

You'll need to gather all of the concurrency and rate values into arrays, then save as csv: 您需要将所有 concurrencyrate值收集到数组中,然后另存为csv:

concurrency, rate = [], []
for cube in root.findall('.//ex:Cube[@currency]', namespaces=namespaces):
    concurrency.append(cube.attrib['concurrency'])
    rate.append(cube.attrib['rate'])

np.savetext('file.csv', (concurrency, rate), delimeter='c')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM