Beautiful Soup 4

参考文献

  1. Beautiful Soup Documentation — Beautiful Soup 4.13.0 documentation. (2025年09月21日参照).
    • に、関数側で特別に定義されていないキーワード引数は自動的に「その属性を持つタグを絞り込むためのフィルタ」として解釈される旨が記されている。

Snippets

HTML 要素を追加・削除 & HTML 要素下の文字列を取得する


from bs4 import BeautifulSoup

def new_tag(soup, tag_name, string):
    tag = soup.new_tag(tag_name)
    tag.string = string
    return tag

text = (
    '<div id="hoge">'
    '<p>Apple</p>'
    'Banana'
    '</div>'
)
soup = BeautifulSoup(text, 'html.parser')

# 要素の追加
p = soup.find('p')
p.append(' Pie')  # <p> 内の末尾に文字列や要素を追加
p.insert_before(new_tag(soup, 'b', 'Coffee'))
p.insert_after(new_tag(soup, 'i', 'Milk'))
assert str(soup) == (
    '<div id="hoge">'
    '<b>Coffee</b>'
    '<p>Apple Pie</p>'
    '<i>Milk</i>'
    'Banana'
    '</div>'
)

# Tag.extract() は要素をツリーから取り除くが取り除いたものは手元に残る
p.extract()
assert str(soup) == (
    '<div id="hoge">'
    '<b>Coffee</b>'
    '<i>Milk</i>'
    'Banana'
    '</div>'
)
assert str(p) == '<p>Apple Pie</p>'

# Tag.decompose() は要素を削除する
soup.find('i').decompose()
assert str(soup) == (
    '<div id="hoge">'
    '<b>Coffee</b>'
    'Banana'
    '</div>'
)

# Tag.get_text() はその要素下の文字列を取得する
div = soup.find('div')
assert div.get_text() == 'CoffeeBanana'

HTML ファイルが参照するスタイルシートのパスを修正する

soup.find()href 属性が css/style.css を含む要素をみつけるには引数 href=lambda v: v and 'css/style.css' in v を指定すればよい。

from bs4 import BeautifulSoup
from pathlib import Path

if __name__ == '__main__':
    root = Path('docs/articles/')
    for article_path in root.glob('*.html'):
        text = article_path.read_text(encoding='utf8')
        soup = BeautifulSoup(text, 'html.parser')

        link = soup.find('link', href=lambda v: v and 'css/style.css' in v)
        link['href'] = '../css/style.css?v=2025-12-09'
        link = soup.find('link', href=lambda v: v and 'css/cookipedia.css' in v)
        link['href'] = '../css/cookipedia.css?v=2025-12-09'
        link = soup.find('script', src=lambda v: v and 'funcs.js' in v)
        link['src'] = '../funcs.js?v=2025-12-09'

        article_path.write_text(str(soup), newline='\n', encoding='utf8')

HTML ファイル内の title 要素を修正する


from bs4 import BeautifulSoup
from pathlib import Path

if __name__ == '__main__':
    root = Path('docs/articles/')
    for article_path in root.glob('*.html'):
        text = article_path.read_text(encoding='utf8')
        soup = BeautifulSoup(text, 'html.parser')
        org = soup.head.title.string
        soup.head.title.string = org.replace(' - Cookipedia', ' - Cookipedia α-version')
        print(soup.head.title.string)
        article_path.write_text(str(soup), newline='\n', encoding='utf8')