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

2024-10-02 20:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的代码:

import requests

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

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

^{pr2}$

该怎么办?在


Tags: 文件代码orgimporthttpurldatawww
2条回答

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

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

如果您决定使用requests,那么请参阅this answer,了解如何编写文件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()

相关问题 更多 >