首页 > 解决方案 > 将html文件插入python文件

问题描述

我在 Windows 10 上使用 Pycharm,我想在 python 文件中使用 html 文件,我该怎么办?我的代码已经写好了,但是网页似乎没有运行这个 html 文件。

为了可视化这一点,我分享了我的代码:

from flask import Flask, render_template

app=Flask(__name__)

@app.route('/')
def home():
    return render_template("home.html")


@app.route('/about/')
def about():
    return render_template("about.html")

if __name__=="__main__":
    app.run(debug=True)

在本地部署这个 python 文件后,我希望这些 html 可以工作,但程序似乎看不到它们。我应该把这些 html 文件放在哪里,或者我应该如何处理它们?我将它们全部放在我电脑上的一个文件夹中。

标签: pythonwindowsflask

解决方案


使用BeautifulSoup. 这是一个示例,在标题标签之后插入了一个元标签,使用insert_after()

from bs4 import BeautifulSoup as Soup

html = """
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div>test</div>
</html>
"""
soup = Soup(html)

title = soup.find('title')
meta = soup.new_tag('meta')
meta['content'] = "text/html; charset=UTF-8"
meta['http-equiv'] = "Content-Type"
title.insert_after(meta)

print soup

印刷:

<html>
    <head>
        <title>Test Page</title>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    </head>
    <body>
        <div>test</div>
    </body>
</html>

您还可以找到 head 标签并在指定位置使用 insert():

head = soup.find('head')
head.insert(1, meta)

另见:


推荐阅读