Python lxml 包装元素
我在想,使用lxml和Python,最简单的方法是什么来把一个元素包裹在另一个元素里?比如说,我有一段HTML代码:
<h1>The cool title</h1>
<p>Something Neat</p>
<table>
<tr>
<td>aaa</td>
<td>bbb</td>
</tr>
</table>
<p>The end of the snippet</p>
我想把这个表格元素用一个
<h1>The cool title</h1>
<p>Something Neat</p>
<section>
<table>
<tr>
<td>aaa</td>
<td>bbb</td>
</tr>
</table>
</section>
<p>The end of the snippet</p>
还有一件我想做的事情是,在XML文档中查找带有特定属性的
标签,然后把所有元素包裹起来,直到下一个标签,比如:
<h1 class='neat'>Subject 1</h1>
<p>Here is a bunch of boring text</p>
<h2>Minor Heading</h2>
<p>Here is some more</p>
<h1 class='neat>Subject 2</h1>
<p>And Even More</p>
<h1 class='neat'>Subject 1</h1>
<p>Here is a bunch of boring text</p>
<h2>Minor Heading</h2>
<p>Here is some more</p>
<h1 class='neat>Subject 2</h1>
<p>And Even More</p>
转换成:
<section>
<h1 class='neat'>Subject 1</h1>
<p>Here is a bunch of boring text</p>
<h2>Minor Heading</h2>
<p>Here is some more</p>
</section>
<section>
<h1 class='neat>Subject 2</h1>
<p>And Even More</p>
</section>
谢谢大家的帮助,
Chris
2 个回答
0
如果你在处理某些xml文件,可以使用BeautifulSoup这个工具,详细信息可以查看这里。
Beautiful Soup是一个很棒的工具,可以把xml文件转成Python对象。这样你就可以用Python的代码来分析这些html内容,并且可以添加或删除标签。比如,你可以写一个叫做is_h1的函数,它会找到xml文件中的所有
标签。然后,你可以使用Beautiful Soup来添加一个标签。
如果你想把处理后的内容返回给浏览器,可以使用HttpResponse,并把最终的xml内容作为字符串传进去。
如果你想把处理后的内容返回给浏览器,可以使用HttpResponse,并把最终的xml内容作为字符串传进去。
7
lxml在处理格式正确的XML时非常棒,但如果你有非XHTML的HTML内容,它就不太好用了。如果是这种情况,可以使用BeautifulSoup,正如systemizer所建议的那样。
使用lxml,有一种相对简单的方法可以在文档中的所有表格周围插入一个部分:
import lxml.etree
TEST="<html><h1>...</html>"
def insert_section(root):
tables = root.findall(".//table")
for table in tables:
section = ET.Element("section")
table.addprevious(section)
section.insert(0, table) # this moves the table
root = ET.fromstring(TEST)
insert_section(root)
print ET.tostring(root)
你也可以做类似的操作来包裹标题,但你需要遍历所有想要包裹的元素,并把它们移动到这个部分里。这里可以用element.index(child)和列表切片来帮助你。