问题描述
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嵌入到类为“ element”的div内的html文件中。我该如何实现?
解决方法
您可以使用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.etree.ElementTree将HTML与常规XML一起使用,也可以更好地使用事实上的标准模板引擎Jinja2及其include
指令。