关闭打开的标签而不包装在<p> </p>中

时间:2015-02-25 19:34:34

标签: python django lxml

我正在尝试为我的表单编写一个干净的方法,这样如果用户留下一个打开的内联标记,它将被关闭,例如:

Here's an <b> open tag  -> Here's an <b> open tag</b>
<i>Here are two <b>open tags -> <i>Here are two <b> open tags</b></i>

我的代码是:

def clean_custom_title(self):
    title = self.cleaned_data.get('custom_title')
    if title:
        title = lxml.etree.tostring(lxml.html.fromstring(title))
    return title

非常接近工作,除了当字符串不是以开放标记开头时,就像我的第一个例子一样,它将所有内容包装在<p>标签中,所以我得到了

Here's an <b> open tag -> <p>Here's an <b> open tag</b></p>

我不能剥离外部标签,因为它们可能是正确的,如我的第二个例子。我并不担心已经包含p标签的可能输入。我可以想象只是用删除<p>删除它们,但这看起来很丑陋和粗暴。

注意,我使用lxml卡住了。我认为BS4也会更好,但这不是我的号召。

1 个答案:

答案 0 :(得分:1)

将所有东西包裹在一次性标签中,然后获取最外面的元素内部内容,如下所示:

def clean_custom_title(self):
    title = self.cleaned_data.get('custom_title')
    if title:
        title = "<foo>%s</foo>"%title
        title = lxml.html.fromstring(title)
        # title = lxml.some_function(title)  # strip <foo> in a 'proper' way
        title = lxml.etree.tostring(title)
        title = title[5:-6] # This is a hack to illustrate the premise
    return title