I would like to add the following tag:
<label 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 the text?
CodePudding user response:
You can use the .append()
function:
label = soup2.new_tag('label')
label['for'] = "cb1"
label['class'] = "indented-checkbox-text"
label.append("Add to favorites")
input.insert_after(label)
Source: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring-and-new-tag
CodePudding user response:
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 for="cb1">Add to favorites</label>',
"html.parser",
)
)
print(soup)
Prints:
<input id="cb1" type="checkbox"/>
<label for="cb1">Add to favorites</label>