python - 将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 文件放在哪里,或者我应该如何处理它们?我将它们全部放在我电脑上的一个文件夹中。
解决方案
使用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)
另见:
推荐阅读
- c# - 从对象中获取特定属性
- spring - 为 CachingConnectionFactory 设置 SSL 连接
- java - 客户端应用程序如何找到服务器(Java)打开的动态选择的 TCP 端口?
- ruby-on-rails-3 - Ruby on Rails:为什么我的数组集包含 null,通过我的 null 检查器?
- user-interface - JavaFX 等待特定事件
- docker - 如何在 docker run 中运行许多命令并保持交互?
- r - 将参数传递给 xgboost 的 mlr 中的预测函数
- r - 单个 Plot 中的多个数据表面,带有使用 Plotly 的按钮
- c - C中数据的抛物线过滤
- laravel - Laravel 中的动态表单字段不应具有相同的值