在 jinja2 中使用 beautifulsoup 和渲染模板解析 HTML

Parse HTML using beautiful soup & render template in jinja2

我正在尝试使用 beautiful soup 解析本地 HTML 文档,然后 render_template() 使用 jinja2 解析结果。

我是 python 的新手,但这是我正在尝试的:

@app.route("inherit/index")
def inheritIndex():
    soup = BeautifulSoup(open("templates/index.html"), "html.parser")
    soup.find(text="foobar").replaceWith("Hooray!")
    return render_template(soup)

我设法直接从 render_template() 方法中替换值。 BeautifulSoup 不是必需的。这是我在评论中建议的解决方案。

HTML:

...
<p> {{ foobar }} lorem ipsum dolor...</p>
... 

Python:

@app.route("inherit/index")
    def inheritIndex():
    return render_template("index.html", foobar="Hooray!")

    # <p> Hooray! lorem ipsum dolor...</p>