Markdown から、amp 対応 の HTML を生成する目的で、BeautifulSoup で、style タグ、script タグ、style属性を除去する方法を調べてみました。
調べた結果を記載します。
BeautifulSoup で、style タグ を除去する
<style>
-HTML5タグリファレンス のHTMLを拝借しました。
decompose
を使うと タグを除去できます。
from bs4 import BeautifulSoup
html = """"
<html lang="ja">
<head>
<title>おすすめの映画</title>
<style>
p.sample {font-weight:bold; color:orange;}
p.sample cite {background:orange; color:white; padding:4px;}
p.sample em {background:yellow;}
</style>
</head>
<body>
<h3>素晴らしき日曜日/黒澤明</h3>
<p class="sample">
<em>おすすめの映画</em>は、黒澤明監督の<cite>素晴らしき日曜日</cite>です。
お金のない若い男女がデートをしながら将来の夢を語り合うというお話ですが、
見終わった後にさわやかな気持ちになれる良作です。
</p>
<p class="sample">
画面の中から観客に語りかける<em>実験的なシーン</em>などもあって、
若き日の黒澤監督のチャレンジ精神が感じられる興味深い作品でもあります。
</p>
</body>
</html>"""
soup = BeautifulSoup(html, "html5lib")
[s.decompose() for s in soup('style')]
soup
<html lang="ja"><head></head><body>"
<title>おすすめの映画</title>
<h3>素晴らしき日曜日/黒澤明</h3>
<p class="sample">
<em>おすすめの映画</em>は、黒澤明監督の<cite>素晴らしき日曜日</cite>です。
お金のない若い男女がデートをしながら将来の夢を語り合うというお話ですが、
見終わった後にさわやかな気持ちになれる良作です。
</p>
<p class="sample">
画面の中から観客に語りかける<em>実験的なシーン</em>などもあって、
若き日の黒澤監督のチャレンジ精神が感じられる興味深い作品でもあります。
</p>
</body></html>
extract
でも同じ結果になります。
soup = BeautifulSoup(html, "html5lib")
[s.extract() for s in soup('style')]
soup
<html lang="ja"><head></head><body>"
<title>おすすめの映画</title>
<h3>素晴らしき日曜日/黒澤明</h3>
<p class="sample">
<em>おすすめの映画</em>は、黒澤明監督の<cite>素晴らしき日曜日</cite>です。
お金のない若い男女がデートをしながら将来の夢を語り合うというお話ですが、
見終わった後にさわやかな気持ちになれる良作です。
</p>
<p class="sample">
画面の中から観客に語りかける<em>実験的なシーン</em>などもあって、
若き日の黒澤監督のチャレンジ精神が感じられる興味深い作品でもあります。
</p>
</body></html>
BeautifulSoup で、script タグ を除去する
除去方法はstyleタグと同様です。
from bs4 import BeautifulSoup
html = """"
<html>
<head>
<script type="text/javascript" language="javascript">
<!--
document.bgColor="#000000";
document.fgColor="#ffffff";
document.linkColor="#0000ff";
document.vlinkColor="#00ff00";
document.alinkColor="#ff0000";
// -->
</script>
</head>
<body>
<a href="../../">トップページ</a>へ戻ります。
</body>
</html>"""
soup = BeautifulSoup(html, "html5lib")
[s.decompose() for s in soup('script')]
soup
<html><head></head><body>"
<a href="../../">トップページ</a>へ戻ります。
</body></html>
soup = BeautifulSoup(html, "html5lib")
[s.extract() for s in soup('script')]
soup
<html><head></head><body>"
<a href="../../">トップページ</a>へ戻ります。
</body></html>
BeautifulSoup で、style 属性を除去する
attrs
が style
であれば削除します。
def remove_attrs(soup, brack_list=tuple()):
for tag in soup.findAll(True):
for attr in [attr for attr in tag.attrs if attr in brack_list]:
del tag[attr]
return soup
from bs4 import BeautifulSoup
html = """
<h1 style="color:blue;text-align:center">This is a header</h1>
<p style="color:green">This is a paragraph.</p>
"""
soup = BeautifulSoup(html, "html5lib")
soup = remove_attrs(soup, ("style",))
soup.body.hidden = True
soup.body
<h1>This is a header</h1>
<p>This is a paragraph.</p>
参考
以下記事が参考になりました。
python - Remove all inline styles using BeautifulSoup - Stack Overflow
コメント