Adding <label> with BeautifulSoup

Viewed 81

I would like to add the following tag:

<label class="indented-checkbox-text" for="cb1">Add to favorites</label>

after

<input id="cb1" type="checkbox"/>

if input is bs4.element.Tag,

    label = soup2.new_tag('label')
    label['for'] = "cb1"
    label['class'] = "indented-checkbox-text"
    input.insert_after(label)

How do I add "Add to favorites" as text?

2 Answers

You can add whole BeautifulSoup() after a Tag:

from bs4 import BeautifulSoup

html_doc = """
<input id="cb1" type="checkbox"/>
"""

soup = BeautifulSoup(html_doc, "html.parser")
inp = soup.select_one("#cb1")

inp.insert_after(
    BeautifulSoup(
        '\n<label class="indented-checkbox-text" for="cb1">Add to favorites</label>',
        "html.parser",
    )
)

print(soup)

Prints:

<input id="cb1" type="checkbox"/>
<label class="indented-checkbox-text" for="cb1">Add to favorites</label>
Related