如何在python中解析本地磁盘文件中的xml?

如何在python中解析本地磁盘文件中的xml?,python,python-3.x,xml-parsing,python-requests,Python,Python 3.x,Xml Parsing,Python Requests,我有这样一个代码: import requests user_agent_url = 'http://www.user-agents.org/allagents.xml' xml_data = requests.get(user_agent_url).content 它将在线xml文件解析为xml\u数据。如何从本地磁盘文件解析它?我尝试替换为本地磁盘路径,但出现错误: raise InvalidSchema("No connection adapters were found for '%

我有这样一个代码:

import requests

user_agent_url = 'http://www.user-agents.org/allagents.xml'
xml_data = requests.get(user_agent_url).content
它将在线xml文件解析为
xml\u数据
。如何从本地磁盘文件解析它?我尝试替换为本地磁盘路径,但出现错误:

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

InvalidSchema: No connection adapters were found

必须做什么?

请注意,您引用的代码并不解析文件-它只是将XML数据放入
XML\u数据中。本地文件的等效项根本不需要使用
请求
:只需编写即可

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

如果您决定使用
请求
,请参阅以了解如何编写文件URL适配器。

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

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

如果您决定使用
请求
,请参阅以了解如何编写文件URL适配器。

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

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

范例

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

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

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

范例

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

请参见:使用:request(获取联机远程文件)获取文件内容,然后使用(解析保存的本地文件)解析它API调用和数据解析:不需要远程文件..文件在我的本地系统中然后使用:docs.python.org/2/library/xml.etree.elementtree.htmlse此:使用:request(获取联机远程文件)获取文件内容然后使用(解析保存的本地文件)API调用和数据解析来解析它:不需要远程文件..文件在我的本地系统中然后使用:docs.python.org/2/library/xml.etree.elementtree.html