【发布时间】:2019-09-21 14:18:44
【问题描述】:
使用 lxml 库,拥有这个 doc xml 文件,我想剥离一些标签并重命名它们:doc.xml
<html>
<body>
<h5>Fruits</h5>
<div>This is some <span attr="foo">Text</span>.</div>
<div>Some <span>more</span> text.</div>
<h5>Vegetables</h5>
<div>Yet another line <span attr="bar">of</span> text.</div>
<div>This span will get <span attr="foo">removed</span> as well.</div>
<div>Nested elements <span attr="foo">will <b>be</b> left</span> alone.</div>
<div>Unless <span attr="foo">they <span attr="foo">also</span> match</span>.</div>
</body>
</html>
而不是 html,body 将所有内容包装在“p 标签”中,而不是使用 h5 和每个 div 来包装所有内容,例如下面使用 lxml 的示例: 我的问题是如何从一种格式以下面的格式包装所有内容?
<p>
<h5 title='Fruits'>
<div>This is some <span attr='foo'>Test</span>.</div>
<div>Some<span>more</span>text.</div>
</h5>
<h5 title='Vegetables'>
<div>Yet another line <span attr='bar'>of</span>text.</div>
....
</h5>
</p>
使用lxml,剥离标签:
tree = etree.tostring(doc.xml)
tree1 = lxml.html.fromstring(tree)
etree.strip_tags(tree1, 'body')
有人对此有任何想法吗?
【问题讨论】:
-
欢迎来到 SO。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。这不是讨论论坛或教程服务。
-
@wwii 忘了问问题
标签: python