使用Flask操作HTML元素的值



我想使用flask来操作HTML元素的属性值。

例如,具有以下HTML:

<html>
<body>
<progress id="result_bar" name="result_bar" max="100" value="50"> </progress>
</body>
</html>

我想将进度属性"值"设置为100(即100%(。

有人能帮忙吗?

THXLazloo

您可以在Flask中创建一个视图,然后从前端对其进行GET/POST以检索或更改进度值。这里有一个最小的例子。

第一个途径是根页面,它呈现一个显示进度条本身的模板,也是更新值的一种方式。[当然,您可以将编辑部分作为一个单独的页面,通过JavaScript以编程方式进行POST等。]

第二个路由是/progress端点,它有一个视图,可以检索或设置进度和最大值。然后,该视图将值存储在Flask的会话存储中,该存储在客户端使用cookie。

app.py:

from flask import Flask, render_template, request, session
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8znxec]/'  # (use random bytes)
def get_progress():
DEFAULT_PROGRESS_VALUE = 0
DEFAULT_PROGRESS_MAX = 100
return {
"value": session.get("progress_value", DEFAULT_PROGRESS_VALUE),
"max": session.get("progress_max", DEFAULT_PROGRESS_MAX),
}
def set_progress_value(val):
if val is not None:
session["progress_value"] = int(val)
def set_progress_max(val):
if val is not None:
session["progress_max"] = int(val)
@app.route("/")
def root():
return render_template("index.html", **get_progress())
@app.route("/progress", methods=["GET", "POST"])
def progress():
if request.method == "POST":
set_progress_value(request.form.get("value"))
set_progress_max(request.form.get("max"))
return get_progress()

templates/index.html:

<!doctype html>
<html>
<body>
<label for="result_bar">Progress:</label>
<progress id="result_bar" max="{{ max }}" value="{{ value }}"></progress>
<hr>
<p>Update progress:</p>
<form action="/progress" method="post">
<input type="number" name="value" value="{{ value }}">
<input type="number" name="max" value="{{ max }}">
<input type="submit" value="Update">
</form>
</body>
</html>

运行它:

flask run

然后,您可以使用表单更改进度值,并重新加载/以查看更改。

有关更多信息,Flask Quickstart是本例中使用的组件的一个很好的参考。

使用烧瓶,直接不使用
Flask是一个创建web应用程序的轻量级库,并不是一个真正好的富html解析器。

但是您可以使用Beautifulsoup来解析Flask应用程序中的请求。

有了html,下面的代码就可以随心所欲了。

from bs4 import BeautifulSoup
html = '<html><body><progress id="result_bar" name="result_bar" max="100" value="50"></progress></body></html>'
soup = BeautifulSoup(html, 'html.parser')
p = soup.find("progress")
p.attrs['value'] = "90"
print(p)

最新更新