【问题标题】:Python: How can I get the current page’s title as a variable in Flask? [closed]Python:如何在 Flask 中获取当前页面的标题作为变量? [关闭]
【发布时间】:2017-12-04 06:48:16
【问题描述】:

假设我有这个 HTML 页面;

<html>
    <head>
        <title>I want this as a variable</title>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

我的应用程序中有一个名为x 的 Python 变量,我怎样才能使x = '我想要这个作为变量'?

【问题讨论】:

    标签: python html python-3.x flask jinja2


    【解决方案1】:

    BeautifulSoup 非常适合: https://www.crummy.com/software/BeautifulSoup/bs4/doc/

    from bs4 import BeautifulSoup
    html_doc = """
    <html>
        <head>
            <title>I want this as a variable</title>
        </head>
        <body>
            <h1>Hello World</h1>
        </body>
    </html>
    """
    
    soup = BeautifulSoup(html_doc, 'html.parser')
    
    x = soup.title.text
    

    【讨论】:

    • 完美运行,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多