python - 剥离一些标签并重命名它们
问题描述
使用 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 tag”中,而不是让 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')
有人对此有任何想法吗?
解决方案
- 创建一个只有标签的新文档。
<p>
- 迭代
<body>
原始文档中标记的后代。- 将标签从原始文档添加到新文档 - 作为其
<p>
标签 的后代- 如果遇到
<h5>
标签;将<h5>
标签添加到<p>
标签- 并将后续标签作为后代添加到它(
<h5>
)
- 并将后续标签作为后代添加到它(
- 如果遇到
- 将标签从原始文档添加到新文档 - 作为其
推荐阅读
- java - 如何使用 volley 从 andorid 中的数据模型回收器视图中获取此信息?
- react-native - FlatList 的推荐项目限制
- java - 如何使用 Java 和 SQLite 将任务分配给 Android Studio 应用程序中的团队
- python - TypeError:“int”对象在 Python 嵌套列表中不可下标
- vaadin - Vaadin Flow 文本字段浏览器自动填充
- c++ - 如何在回文中使用入队、出队、推送和窥视?
- c++ - Google 测试翻译单元文件中的函数
- r - Neuralnet 封装阈值和神经元数量
- mysql - 当我尝试运行 sql 脚本时出现 MySQL Workbench 错误
- javascript - 如何在javascript中管理带有原始字节的文件