【问题标题】:How to parse xml from local disk file in python?如何从python中的本地磁盘文件解析xml?
【发布时间】:2018-09-12 08:25:44
【问题描述】:

我有这样的代码:

import requests

user_agent_url = 'http://www.user-agents.org/allagents.xml'
xml_data = requests.get(user_agent_url).content

这会将在线 xml 文件解析为 xml_data。如何从本地磁盘文件中解析它?我尝试用本地磁盘的路径替换,但出现错误:

raise InvalidSchema("No connection adapters were found for '%s'" % url)

InvalidSchema: No connection adapters were found

必须做什么?

【问题讨论】:

标签: python python-3.x xml-parsing python-requests


【解决方案1】:

请注意,您引用的代码不会解析文件 - 它只是将 XML 数据放入xml_data。本地文件的等效项根本不需要使用requests:只需编写

with open("/path/to/XML/file") as f:
    xml_data = f.read()

如果您确定要使用requests,请参阅this answer,了解如何编写文件 URL 适配器。

【讨论】:

    【解决方案2】:

    您可以使用open方法读取文件内容,然后使用elementtree模块XML函数对其进行解析。

    它返回一个你可以循环的etree对象。

    例子

    Content = open("file.xml").read()
    From xml.etree import XML
    Etree = XML(Content)
    Print Etree.text, Etree.value, Etree.getchildren()
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2023-03-13
      相关资源
      最近更新 更多