python-lxml如何按标记名获取元素的子元素?

2024-09-23 10:21:07 发布

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

我有一个xml文件,如下所示:

<page>
    <title>title1</title>
    <subtitle>subtitle</subtitle>
    <ns>0</ns>
    <id>1</id>
    <text>hello world!@</text>
</page>
<page>
    <title>title2</title>
    <ns>0</ns>
    <id>1</id>
    <text>hello world</text>
</page> 

我怎样才能得到每页的正文?现在我有每一页的清单。下面的代码将打印第二个page元素的文本,而不是第一个。是否有方法按标记名获取子元素,如element['text']

for i in pages:
    print i[3]

Tags: 文件代码textid元素helloworldtitle
3条回答

为了简化这个问题,我使用了一个“Node”助手类来返回dict:

class Node():
    @staticmethod
    def childTexts(node):
        texts={}
        for child in list(node):
            texts[child.tag]=child.text
        return texts  

示例用法:

xml = """<pages>
<page>
    <title>title1</title>
    <subtitle>subtitle</subtitle>
    <ns>0</ns>
    <id>1</id>
    <text>hello world!@</text>
</page>
<page>
    <title>title2</title>
    <ns>0</ns>
    <id>1</id>
    <text>hello world</text>
</page>
</pages>

"""

root = etree.fromstring(xml)
for node in root.xpath('//page'):
    texts=Node.childTexts(node)
    print (texts)

结果:

{'title': 'title1', 'subtitle': 'subtitle', 'ns': '0', 'id': '1', 'text': 'hello world!@'}
{'title': 'title2', 'ns': '0', 'id': '1', 'text': 'hello world'}

This tutorial帮助我完成了类似的任务:

每次迭代都会找到一个名为“id”或“text”的标记。如果找不到标记,则返回字符串“None”。一次迭代的结果将被追加到一个列表中,允许我们以类似于数据帧的格式打印该列表。

import lxml
import lxml.etree as ET

# Initialise a list to append results to
list_of_results = []

# Loop through the pages to search for text
for page in root:
    id = page.findtext('id', default = 'None')
    text = page.findtext('text', default = 'None')
    list_of_results.append([id, text])

# Print list
list_of_results

结果:

[['1', 'hello world!@'], ['1', 'hello world']]

如果只想打印文本,只需删除id行即可。

您可以编写如下代码:

from lxml import html

xml = """<page>
    <title>title1</title>
    <subtitle>subtitle</subtitle>
    <ns>0</ns>
    <id>1</id>
    <text>hello world!@</text>
</page>
<page>
    <title>title2</title>
    <ns>0</ns>
    <id>1</id>
    <text>hello world</text>
</page>"""

root = html.fromstring(xml)
print(root.xpath('//page/text/text()'))

结果将是:

['hello world!@', 'hello world']

相关问题 更多 >