如何使用 Python 将 html 嵌入到 html 文件
how to embed html to html file using Python
file.html:
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Hey</title>
</head>
<body>
<div class='element'></div>
</body>
</html>
Python代码:
html = '<div id="child">Hello</div>
我想将 Python 代码中的 html 嵌入到 div 内的 html 文件中,其中包含 class“元素”。我怎样才能做到这一点?
您可以使用 BeautifulSoup 进行此类更改,如下所示。您可以阅读更多关于 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 一样使用 HTML 使用 xml.etree.ElementTree or better use de-facto standard templating engine Jinja2 and its include
指令。
file.html:
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Hey</title>
</head>
<body>
<div class='element'></div>
</body>
</html>
Python代码:
html = '<div id="child">Hello</div>
我想将 Python 代码中的 html 嵌入到 div 内的 html 文件中,其中包含 class“元素”。我怎样才能做到这一点?
您可以使用 BeautifulSoup 进行此类更改,如下所示。您可以阅读更多关于 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 一样使用 HTML 使用 xml.etree.ElementTree or better use de-facto standard templating engine Jinja2 and its include
指令。