py-py’s blog

何か書くよ

タグ内のテキストの一部に別タグを付けたい(20190625追記)

こんな感じのhtmlがあるとする(一部抜粋)

<div class="hogehoge">第一回 天下一武道会を開始する。うわ、ビルズ様つえぇなあ。</div>

この「第一回」という文字に対し何らかのタグを付与したい。

例えば太字にしたいとか。 BeautifulSoupのnew_tagをそのまま使うとhogehoge全体が太字になってしまい、悩んでしまった。

この処理をしたいときのコードが以下。

from bs4 import BeautifulSoup

content_html = BeautifulSoup(html, "html.parser")
content_body = content_html.find_all("main-area")
for content in content_body:
    for div in content.find_all("div", class_="hogehoge"):
        idx = div.text.find(" ")
        if idx != -1:
            tag = content_html.new_tag("b")
            tag.string = div.contents[0].string[:idx + 1]
            div.contents[0].replace_with(contentHtml.new_string(div.contents[0].string[idx+1:]))

後で見直しましょう。 「div.contents[0].replace_with(contentHtml.new_string(div.contents[0].string[idx+1:]))」が二重for文の外で処理されるように見えるが、本来は「tag.string = div.contents[0].string[:idx + 1]」と同じインデント。

【20190625追記】

上記のコードだと何も起こらない。 div.contents[0].replace_with()~の直後に以下を追記する。

from bs4 import BeautifulSoup

content_html = BeautifulSoup(html, "html.parser")
content_body = content_html.find_all("main-area")
for content in content_body:
    for div in content.find_all("div", class_="hogehoge"):
        idx = div.text.find(" ")
        if idx != -1:
            tag = content_html.new_tag("b")
            tag.string = div.contents[0].string[:idx + 1]
            div.contents[0].replace_with(contentHtml.new_string(div.contents[0].string[idx+1:]))
            # 以下を追記
            div.insert(0, tag)