from xml.dom.minidom import parse, parseString
datasource = open('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml')
dom = parse(datasource)
print dom
... 上面的代码抛出一个 IOError: 2, 'No such file or directory'
。 Python 不像 PHP 那样读取远程文档?我需要更改代码中的哪些内容才能使其读取 XML 文件?
谢谢
最佳答案
使用 urllib2.urlopen()
:
>>> import urllib2
>>> from xml.dom.minidom import parse, parseString
>>> u1=urllib2.urlopen('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml')
>>> dom=parse(u1)
>>> print dom
<xml.dom.minidom.Document instance at 0x017D73A0>
>>> dom.childNodes
[<DOM Element: gesmes:Envelope at 0x17d7c88>]
>>> dom.childNodes[0].childNodes
[<DOM Text node "u'\n\t'">, <DOM Element: gesmes:subject at 0x1041aa8>,
<DOM Text node "u'\n\t'">, <DOM Element: gesmes:Sender at 0xff8260>,
<DOM Text node "u'\n\t'">, <DOM Element: Cube at 0x17d3dc8>, <DOM Text node "u'\n'">]
>>>
此 XML 使用 Cube
标记来构建太多结构,因此选择货币有点让人头疼。
>>> [elem.attributes['currency'].value for elem in
dom.getElementsByTagName('Cube') if elem.hasAttribute('currency')]
[u'USD', u'JPY', u'BGN', u'CZK', u'DKK', u'EEK', u'GBP', u'HUF', u'LTL', u'LVL',
u'PLN', u'RON', u'SEK', u'CHF', u'NOK', u'HRK', u'RUB', u'TRY', u'AUD', u'BRL',
u'CAD', u'CNY', u'HKD', u'IDR', u'INR', u'KRW', u'MXN', u'MYR', u'NZD', u'PHP',
u'SGD', u'THB', u'ZAR']
>>>
关于python - 在 Python 中打开远程文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2091598/