Reputation: 365
file.html:
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Hey</title>
</head>
<body>
<div class='element'></div>
</body>
</html>
Python code:
html = '<div id="child">Hello</div>
I want to embed the html in the Python code into the html file inside the div with class "element". How can I achieve this?
Upvotes: 2
Views: 694
Reputation: 797
You can do such changes using BeautifulSoup as below. You can read more about BeautifulSoup
from bs4 import BeautifulSoup as Soup
with open('<file_path>') as f:
soup = Soup(f)
elementDiv = soup.find('div', {"class": "element"}) # find div with class name as element
newDiv = soup.new_tag('div') # adds a new tag
newDiv['id'] = "child"
newDiv.string = "Hello"
elementDiv.append(newDiv) # appends the newDiv within the elementDiv
print(soup)
Upvotes: 1
Reputation: 7295
You could either work with HTML as with regular XML using xml.etree.ElementTree or better use de-facto standard templating engine Jinja2 and its include
directive.
Upvotes: 1