Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当元素位于文本之间时提取xml文本_Python_Xml_Parsing_Xml Parsing - Fatal编程技术网

Python 当元素位于文本之间时提取xml文本

Python 当元素位于文本之间时提取xml文本,python,xml,parsing,xml-parsing,Python,Xml,Parsing,Xml Parsing,我有一个xml文件: 这里有一些文字 ) 这是我用来解析和浏览文件的简单代码: 将xml.etree.ElementTree作为ET导入 tree=ET.parse(文件路径) root=tree.getroot() def explore_元素(元素): 打印(element.tag) 打印(element.attrib) 打印(element.text) 对于元素中的子元素: 探索元素(子元素) 探索_元素(根) 除了元素没有完整的文本之外,一切都按预期进行。特别是,我似乎缺少了“但是

我有一个xml文件:


这里有一些文字 )

这是我用来解析和浏览文件的简单代码:

将xml.etree.ElementTree作为ET导入
tree=ET.parse(文件路径)
root=tree.getroot()
def explore_元素(元素):
打印(element.tag)
打印(element.attrib)
打印(element.text)
对于元素中的子元素:
探索元素(子元素)
探索_元素(根)
除了元素
没有完整的文本之外,一切都按预期进行。特别是,我似乎缺少了“但是还有一些东西”(

元素后面的文本)

xml文件是给定的,因此我无法对其进行改进,即使有更好的编写方法(而且有太多的问题需要手动修复)

有什么方法可以让我得到所有的文本吗

我的代码生成的输出(如果有帮助的话)如下所示:

do
{'title':'Example document','date':'today'}
分贝
{'descr':'First level'}
P
{}
这里有一些文字
af
{'d':'reference 1'}
继续
编辑

被接受的答案让我意识到我没有尽可能仔细地阅读文档。有相关问题的人也可能会发现.tail很有用。

使用BeautifulSoup:

list_test.xml:

<do title='Example document' date='today'>
<db descr='First level'>
    <P>
        Some text here that
        <af d='reference 1'>continues</af>
        but then has some more stuff.
    </P>
</db>
输出:

Some text here that
continues
but then has some more stuff.
Some text here that continues but then has some more stuff.
编辑:

使用elementree:

import xml.etree.ElementTree as ET
xml = '<p> Some text here that <af d="reference 1">continues</af> but then has some more stuff.</p>'
tree = ET.fromstring(xml)
print(''.join(tree.itertext()))

我们可以使用
beautifulsoup
吗?我看到你们提供了两种解决方案,所以这很完美。让我看看能不能成功!
Some text here that continues but then has some more stuff.