在Python中解析XML时出现意外结果

2024-06-16 12:13:41 发布

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

我试图从XML中解析以下文本

title_text = word1 Word2 word3 word4

问题是,使用下面的代码,我得到了title_text = 'word1'

我怎样才能做到这一点

XML:

<response>...<results>...<grouping>...<group>...
    <doc>...
         <title>
             word1
             <hlword>Word2</hlword>
             <hlword>word3</hlword>
             word4
          </title>
          ...
    </doc>
</group>...</grouping>...</results>...</response>...

解析代码:

from lxml import objectify
...
tree = objectify.fromstring(xml)
nodes = tree.response.results.grouping.group
for node in nodes:
    title_element = node.doc.title
    title_text = title_element.text
    print title_text

Tags: 代码textdoctitleresponsegroupxmlresults
1条回答
网友
1楼 · 发布于 2024-06-16 12:13:41

只需在.itertext()上迭代:

>>> for node in nodes:
...    print(' '.join(node.doc.title.itertext()))
...
word1 word2 word3 word4

相关问题 更多 >