在python中解析XML文件以进行电子邮件发送

2024-03-28 21:37:33 发布

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

我用python编写的代码不仅可以读取xml,还可以通过电子邮件发送解析结果。现在我在尝试读取xml格式的文件时遇到了麻烦。我做了一个简单的python脚本,我认为它至少可以读取这个文件,然后我可以尝试在python中发送电子邮件,但是我在第4行得到了一个语法错误。在

在根.tag'日志'

不管怎样,这是我目前为止写的代码:

import xml.etree.cElementTree as etree

tree = etree.parse('C:/opidea.xml')
response = tree.getroot()
log = response.find('log').text
logentry = response.find('logentry').text
author = response.find('author').text
date = response.find('date').text
msg = [i.text for i in response.find('msg')]

现在xml文件具有这种格式

^{pr2}$

我希望能够发送这个xml文件的电子邮件。目前,我只想让python代码读取xml文件。在


Tags: 文件代码textlogtreedate电子邮件response
1条回答
网友
1楼 · 发布于 2024-03-28 21:37:33

response.find('log')找不到任何内容,因为:

find(self, path, namespaces=None)

Finds the first matching subelement, by tag name or path.

在您的例子中,log不是子元素,而是根元素本身。但是,您可以直接获得它的文本:response.text。但是在您的示例中,log元素中没有任何文本。在

编辑:抱歉,文档中的引用实际上适用于lxml.etree文档,而不是{}。在

我不确定原因,但是对find的所有其他调用也返回None(可以通过打印response.find('date')等方法找到)。使用^{}可以使用xpath代替:

author = response.xpath('//author')[0].text
msg = [i.text for i in response.xpath('//msg')]

无论如何,您对find的使用对于msg都是不正确的,因为find总是返回单个元素,而不是它们的列表。在

相关问题 更多 >