【问题标题】:Python ElementTree XML IOError: [Errno 22] invalid mode ('rb') or filenamePython ElementTree XML IOError: [Errno 22] 无效模式 ('rb') 或文件名
【发布时间】:2014-04-25 16:50:10
【问题描述】:

使用以下代码:

import xml.etree.cElementTree as ET
tree = ET.parse(r'https://apitest.batchbook.com/api/v1/people.xml?auth_token=GR5doLv88FrnLyLGIwok')

我收到错误消息:

IOError                                   Traceback (most recent call last)
<ipython-input-10-d91d452da3e7> in <module>()
----> 1 tree = ET.parse(r'https://apitest.batchbook.com/api/v1/people.xml?auth_token=GR5doLv88FrnLyLGIwok')

<string> in parse(source, parser)

<string> in parse(self, source, parser)

IOError: [Errno 22] invalid mode ('rb') or filename: 'https://apitest.batchbook.com/api/v1/people.xml?auth_token=GR5doLv88FrnLyLGIwok'

但是,如果我在浏览器中打开上面的链接,并将其保存到 XML 文件 (people.xml),然后执行以下操作:

tree = ET.parse(r'C:\Users\Eric\Downloads\people.xml')
tree.getroot()

我得到结果:

关于为什么使用链接不起作用的任何线索?谢谢:)

【问题讨论】:

  • etree 不包含 HTTP 库。它仅适用于字符串或本地文件。您必须使用urllib2requests 下载xml,然后在本地进行解析。

标签: python xml xml-parsing elementtree


【解决方案1】:

在您的文件系统中的任何地方都没有该名称的文件。 etree 不明白这真的是一个网址,即使这样做也无法对它做任何事情。

相反,您应该执行以下操作:

import xml.etree.cElementTree as ET
import urllib2, StringIO

page_with_xml = urllib2.urlopen(r'https://apitest.batchbook.com/api/v1/people.xml?auth_token=GR5doLv88FrnLyLGIwok')
io_xml = StringIO.StringIO()
io_xml.write(page_with_xml.read())
io_xml.seek(0)
tree = ET.parse(io_xml)

已编辑以纠正 etree.parse 正在寻找类似文件的对象这一事实。不是特别优雅,但它可以完成工作。

【讨论】:

  • 谢谢。那行得通。有点。在解析时,我得到“IOError in ()”和“IOError: [Errno 2] No such file or directory”。然后它继续打印 XML 文件的内容 ('\n\n 1 \n...)。奇怪...
  • @mzjn - 是的,我忘记了。使用 StringIO 中的 parse 更新。
  • StringIO 不需要。 urllib2.urlopen() 返回一个类似文件的对象。
  • 是的。仅适用于 page_with_xml = urllib2.urlopen(r'apitest.batchbook.com/api/v1/…) tree = ET.parse(page_with_xml)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-05
相关资源
最近更新 更多