Python と BeautifulSoup の初心者。「example.html」というファイルを開き、BeautifulSoup アクションを実行し、次にブリーチ アクションを実行し、結果をファイル「example-cleaned.html」として保存する Python プログラムがあります。これまでのところ、「example.html」のすべてのコンテンツで機能しています。
フォルダー「/posts/」内の各ファイルを開き、その上でプログラムを実行し、「/posts-cleaned/X-cleaned.html」として保存するように変更する必要があります。X は元のファイル名です。
最小化された私のコードは次のとおりです。
from bs4 import BeautifulSoup
import bleach
import re
text = BeautifulSoup(open("posts/example.html"))
text.encode("utf-8")
tag_black_list = ['iframe', 'script']
tag_white_list = ['p','div']
attr_white_list = {'*': ['title']}
# Step one, with BeautifulSoup: Remove tags in tag_black_list, destroy contents.
[s.decompose() for s in text(tag_black_list)]
pretty = (text.prettify())
# Step two, with Bleach: Remove tags and attributes not in whitelists, leave tag contents.
cleaned = bleach.clean(pretty, strip="TRUE", attributes=attr_white_list, tags=tag_white_list)
fout = open("posts/example-cleaned.html", "w")
fout.write(cleaned.encode("utf-8"))
fout.close()
print "Done"
喜んで受け取った既存のソリューションへの支援と指針!