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?
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)
您可以使用xml.etree.ElementTree像使用常规 XML 一样使用 HTML,或者更好地使用事实上的标准模板引擎 Jinja2 及其include
指令。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.