lxml etree将<em></em>替换为<em/>

2024-05-08 01:41:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个博客,我把博客文章保存为数据库中的HTML字符串(基本上是HTML元素的文本)。例如:我创建了一个博客文章,它导致以下字符串作为我的博客文章内容。你知道吗

<p>asdasd</p><p><em></em><div>another string</div>

当用户来查看帖子时,我从DB检索上面的内容,并使用lxml etree对内容做一些处理(这与我的问题无关),然后将内容返回到浏览器。你知道吗

from lxml import etree as ET
obj = ET.parse(StringIO.StringIO(self.text), parser=ET.HTMLParser()) #self.text holds the html string of blog post
return ET.tostring(tree) # return the html string to browser

现在问题是发送到浏览器的内容如下

<p>asdasd</p><p></em /><div>another string</div>

这会导致chrome浏览器出现各种各样的问题,例如,在用户浏览器上,上面的html将显示如下(chrome自动尝试修复后)

<p>asdasd</p><p></em><div>another string</div></em>

有没有办法防止lxml etree在解析时更改html内容?似乎etree对所有空的html元素都这样做。如果我放一个 <div></div>然后将其替换为<div />


Tags: 字符串div元素内容stringhtml文章another
1条回答
网友
1楼 · 发布于 2024-05-08 01:41:01

下面是一些您想使用lxml在Python中尝试XML规范化(C14N)的内容:

从这个来源https://www.w3.org/TR/xml-c14n/我们读到:

Empty elements are converted to start-end tag pairs

示例代码:

from lxml import etree
xml = "<main><p>asdasd</p><p><em></em><div>another string</div></p></main>"
root_element = etree.XML(xml)
print(etree.tostring(root_element, method="c14n")))

输出

b'<main><p>asdasd</p><p><em></em><div>another string</div></p></main>'

相关问题 更多 >