【问题标题】:Insert string into html file using python beautifulsoup使用 python beautifulsoup 将字符串插入 html 文件
【发布时间】:2021-03-08 21:18:57
【问题描述】:

我想通过使用 python(如果可能的话,通过 Beautifulsoup)将像 {% load static %} 这样的字符串插入现有 html 文件的第一行(在最顶部)。所以从这里:

<!DOCTYPE html>
<html>
<body>

</body>
</html>

我希望结果是这样的。所以我可以运行 python 脚本并将这一行插入到我拥有的所有现有 html 文件中。

{% load static %}
<!DOCTYPE html>
<html>
<body>
    
</body>
</html>

【问题讨论】:

    标签: javascript python html css beautifulsoup


    【解决方案1】:

    您可以使用insert_before() 方法在DOCTYPE 之前添加一个字符串。

    from bs4 import BeautifulSoup
    
    html = '''
    <!DOCTYPE html>
    <html>
    <body>
    </body>
    </html>
    '''
    
    soup = BeautifulSoup(html, "html.parser")
    
    soup.contents[0].insert_before('{% load static %} \n')
    
    print(soup.prettify())
    

    输出:

    {% load static %}
    <!DOCTYPE html>
    <html>
     <body>
     </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      这可能是您在此处寻找的内容:Prepend line to beginning of a file 您可以循环它并让它针对您需要更新的所有文件运行。

      【讨论】:

        猜你喜欢
        • 2015-09-22
        • 2020-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-20
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多