Skip to main content
 首页 » 编程设计

python之如何在 python 中使用 lxml 去除 xml 标签中的所有子标签,但保留文本合并到 parens

2025年05月04日13Terrylee

如何告诉 etree.strip_tags() 从给定的标签元素中去除所有可能的标签?

我必须自己映射它们吗,比如:

STRIP_TAGS = [ALL TAGS...] # Is there a built in list or dictionary in lxml 
                           # that gives you all tags? 
etree.strip_tags(tag, *STRIP_TAGS) 

也许是我不知道的更优雅的方法?

示例输入:

parent_tag = "<parent>This is some <i>text</i> with multiple <some_tag>tags</some_tag> and sometimes they <tt>are<bold> nested</bold></tt>.</parent>" 

期望的输出:

# <parent>This is some text with multiple tags and sometimes they are nested.</parent> 

甚至更好:

This is some text with multiple tags and sometimes they are nested. 

请您参考如下方法:

您可以使用 lxml.html.clean模块:

import lxml.html, lxml.html.clean 
 
 
s = '<parent>This is some <i>text</i> with multiple <some_tag>tags</some_tag> and sometimes they <tt>are<bold> nested</bold></tt>.</parent>' 
 
tree = lxml.html.fromstring(s) 
cleaner = lxml.html.clean.Cleaner(allow_tags=['parent'], remove_unknown_tags=False) 
cleaned_tree = cleaner.clean_html(tree) 
 
print lxml.etree.tostring(cleaned_tree) 
# <parent>This is some text with multiple tags and sometimes they are nested.</parent>