You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用lxml获取元素内全部文本及子元素并访问指定内容?

解决XML 标签内容提取与文本访问问题

问题原因

你当前脚本里的elem.text只能获取<para>元素的第一个直接文本节点,而<para>内部包含多个文本节点和子元素(如<child1>、<child2>、<child3>),所以只能输出开头部分内容,拿不到后续的文本(包括末尾的"Young")。

解决方案

要同时保留元素结构(用于判断子标签是否存在)、获取全部内容(含子元素)以及访问所有文本,可按以下方式修改脚本:

1. 保留元素对象并判断子标签存在性

直接通过<para>元素对象的find()方法就能检查特定子标签(如<child3>)是否存在:

import xml.etree.ElementTree as ET
import copy

xml_content = "<root><para>Brother set had private his letters observe outward resolve. Shutters ye marriage to throwing we as. <child1>Effect in if agreed he wished wanted admire expect</child1>. Or shortly visitor is comfort <child2>placing to cheered do</child2>. Few hills tears are weeks saw. Partiality insensible celebrated is in. Am <child3>offended as wandered</child3>thoughts greatest an friendly. Evening covered in he exposed fertile to. Horses seeing at played plenty nature to expect we. Young say led stood hills own thing get</para></root>"

parser = ET.XMLParser(remove_blank_text=True)
root = ET.XML(xml_content, parser=parser)

# 深拷贝获取<para>元素(保留原结构)
def get_deep_copy(element):
    return copy.deepcopy(element)

new_para_elements = [get_deep_copy(para) for para in root.findall('.//para')]

for elem in new_para_elements:
    # 判断child3是否存在
    if elem.find('.//child3') is not None:
        print("存在child3标签")
    else:
        print("不存在child3标签")

2. 获取内的全部文本(包括子元素和末尾的"Young")

递归遍历<para>下的所有节点,提取所有文本内容:

def extract_all_text(element):
    text = element.text or ""
    for child in element:
        text += extract_all_text(child)
        text += child.tail or ""
    return text

for elem in new_para_elements:
    full_text = extract_all_text(elem)
    print("\n全部文本内容:")
    print(full_text)
    # 检查是否包含"Young"
    if "Young" in full_text:
        print("\n已找到文本'Young'")

3. 输出的完整结构(带标签)

将元素序列化为字符串,查看<para>的完整XML内容:

for elem in new_para_elements:
    print("\n<para>完整结构:")
    print(ET.tostring(elem, encoding='unicode'))

完整整合脚本

import xml.etree.ElementTree as ET
import copy

xml_content = "<root><para>Brother set had private his letters observe outward resolve. Shutters ye marriage to throwing we as. <child1>Effect in if agreed he wished wanted admire expect</child1>. Or shortly visitor is comfort <child2>placing to cheered do</child2>. Few hills tears are weeks saw. Partiality insensible celebrated is in. Am <child3>offended as wandered</child3>thoughts greatest an friendly. Evening covered in he exposed fertile to. Horses seeing at played plenty nature to expect we. Young say led stood hills own thing get</para></root>"

parser = ET.XMLParser(remove_blank_text=True)
root = ET.XML(xml_content, parser=parser)

def get_deep_copy(element):
    return copy.deepcopy(element)

new_para_elements = [get_deep_copy(para) for para in root.findall('.//para')]

def extract_all_text(element):
    text = element.text or ""
    for child in element:
        text += extract_all_text(child)
        text += child.tail or ""
    return text

for elem in new_para_elements:
    # 检查子标签
    if elem.find('.//child3'):
        print("检测到child3标签")
    
    # 获取全部文本
    full_text = extract_all_text(elem)
    print("\n完整文本:")
    print(full_text)
    
    # 查看完整结构
    print("\n完整XML结构:")
    print(ET.tostring(elem, encoding='unicode'))

内容的提问来源于stack exchange,提问作者user1958532

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:48:10