【发布时间】:2014-01-16 14:47:32
【问题描述】:
我有一些代码,作为其运行的一部分,为了输出,它获取一个 HTML 文档并将其修改为另一种形式。 (本质上是 HTML 到 BBCode。)
我目前正在通过定义 XPath 和替换的字典来执行此操作,然后使用 lxml 中的工具迭代字典:
change_xpaths = {
XPath(".//span[contains(@style, 'font')]") : "font",
XPath(".//span[contains(@style, 'color')]") : "color",
XPath(".//span[contains(@style, 'size')]") : "size"
}
replace_xpaths = {
XPath(".//span[@style='text-decoration: underline']") : "u",
XPath(".//span[@style='text-decoration: line-through']") : "s",
XPath(".//div[@style='padding-left: 30px']") : "remove"
}
def _clean_text(cls, raw):
for ele in cls.struck_through_xpath(raw):
ele.getparent().remove(ele)
for xp, repl in cls.replace_xpaths.items():
for ele in xp(raw):
ele.attrib.pop("style")
ele.tag = repl
for xp, chng in cls.change_xpaths.items():
for ele in xp(raw):
ele.tag = chng
for br in raw.xpath(".//br"):
try:
br.tail = "\n" + br.tail
except TypeError:
br.tail = "\n"
strip_elements(raw, 'img', with_tail = False)
strip_elements(raw, 'br', with_tail = False)
strip_tags(raw, 'remove')
(这确实是类定义的一部分。)
我知道我也可以使用 xslt 转换来做到这一点。
首先,我想要一个确认,我确实可以使用 xslt 完成所有这些操作,即用非标准标签替换一些标签,并在保留其文本或尾部内容的同时彻底删除标签。
其次,我想知道这样做是否可以显着提高性能?我怀疑是这样,但是,我似乎在互联网上找不到太多关于此的信息。
【问题讨论】: