从Python类写入HTML文件可以通过以下步骤实现:
from jinja2 import Environment, FileSystemLoader
class HTMLGenerator:
def __init__(self, title):
self.title = title
self.content = []
def add_heading(self, text):
self.content.append(f"<h1>{text}</h1>")
def add_paragraph(self, text):
self.content.append(f"<p>{text}</p>")
def generate_html(self):
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html')
output = template.render(title=self.title, content=''.join(self.content))
with open('output.html', 'w') as file:
file.write(output)
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
{{ content }}
</body>
</html>
if __name__ == '__main__':
generator = HTMLGenerator('My HTML Page')
generator.add_heading('Welcome to my website!')
generator.add_paragraph('This is a paragraph.')
generator.generate_html()
这样,就可以通过调用Python类中的方法来生成HTML内容,并将其写入到output.html文件中。可以根据需要扩展HTMLGenerator类,添加更多的方法来生成不同的HTML元素和结构。
领取专属 10元无门槛券
手把手带您无忧上云