2024-10-02 20:30:52 发布
网友
我有这样的代码:
import requests user_agent_url = 'http://www.user-agents.org/allagents.xml' xml_data = requests.get(user_agent_url).content
它将把一个在线xml文件解析成xml_data。如何从本地磁盘文件解析它?我尝试替换为本地磁盘的路径,但出现错误:
xml_data
该怎么办?在
请注意,您引用的代码并不解析文件—它只是将XML数据放入xml_data。本地文件的等价物根本不需要使用requests:只需写
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()
请注意,您引用的代码并不解析文件—它只是将XML数据放入
xml_data
。本地文件的等价物根本不需要使用requests
:只需写如果您决定使用
requests
,那么请参阅this answer,了解如何编写文件URL适配器。在您可以使用open方法读取文件内容,然后使用elementtree模块XML函数对其进行解析。在
它返回一个etree对象,您可以循环该对象。在
示例
相关问题 更多 >
编程相关推荐