py-py’s blog

何か書くよ

BeautifulSoupオブジェクトをhtmlに変換する

BeautifulSoupで既存のhtmlを加工した後、htmlとして使いたいときに以下の関数を利用する。

soup.prettify()

from bs4 import BeautifuSoup, ResultSet

html : str = ""
with open("hoge.html", "r", encoding-"utf-8") as f:
    html = f.read()

soup = BeautifulSoup(html, "html.parser")

"""
何かの処理
アンカの消去、styleの書き換え等々
"""
all_table: ResultSet = soup.find_all("table", attrs={"class", "hoge"})
for table in all_table:
    if table["style"] == "border-collapse: separete;":
        del table["style"]
        table["style"] = "border-collapse: collapse;"

with open("Edited_" + "hoge.html", "w", encoding="utf-8") as f:
    html: object = soup.prettify()
    f.write(html)