如何使用Python将html嵌入html文件

问题描述

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指令。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...