问题描述
<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 %}}'
。