搜索并用类名替换HTML标记,并用非HTML标记替换

问题描述

我想用类名“ figure”替换所有div标记

<div class="figure">
    <p>Some content.</p>
</div>

带有非HTML标记(在我的情况下是Hugo shortcode

{{% row %}}
    <p>Some content.</p>
{{% /row %}}

replace html tags with other html tags很容易,但是如果涉及到非HTML标记,我不知道该怎么做。

解决方法

我看不到“简单”的解决方案,因为短代码也可以包含/<>个字符,因此您不能将它们作为文档树的一部分。 / p>

一种解决方案是将<div class="figure">替换为自定义标签,最后将这些自定义标签替换为您的简码:

from bs4 import BeautifulSoup

txt = '''
<div>
    <div class="figure">
        <p>Some content.</p>
    </div>
</div>

<div class="figure">
    <p>Some other content.</p>
</div>
'''

soup = BeautifulSoup(txt,'html.parser')

for div in soup.select('div.figure'):
    t = soup.new_tag('xxx-row')
    t.contents = div.contents
    div.replace_with(t)

s = str(soup).replace('<xxx-row>','{{% row %}}')
s = s.replace('</xxx-row>','{{% /row %}}')

print(s)

打印:

<div>
{{% row %}}
<p>Some content.</p>
{{% /row %}}
</div>
{{% row %}}
<p>Some other content.</p>
{{% /row %}}
,

如果您使用记事本或其他任何具有search and replace的文本编辑器

您可以替换的功能

'<div class="figure">''{{% row %}}''</div>''{{% /row %}}'

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...