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



我想用类名"figure"替换所有div标签

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

带有非 HTML 标签(在我的情况下是 Hugo 短代码)

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

用其他 html 标签替换 html 标签很容易,但如果涉及非 html 标签,我不知道该怎么做。

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

一种解决方案是将<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 %}}'.

最新更新