2

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

What if the html file is big? Can I create Soup object given a file path ?
@Petar It is possible. I have updated the answer now where I am reading from the HTML file
Thank you! Good solution :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.