【问题标题】:Making beautiful soup play nice with handlebars用车把制作漂亮的汤
【发布时间】:2014-03-20 12:29:45
【问题描述】:

我正在编写一个脚本来重构模板增强的 html。

我希望 beautifulsoup 逐字打印 {{ }} 中的任何代码,而不将 > 或其他符号转换为 html 实体。

需要将一个包含多个模板的文件拆分成多个文件,每个文件都有一个模板。

规格:splitTemplates templates.html templateDir 必须:

  1. 阅读templates.html
  2. 对于每个<template name="xxx">contents {{ > directive }}</template>,将此模板写入文件templateDir/xxx

代码sn-p:

soup = bs4.BeautifulSoup(open(filename,"r"))
for t in soup.children:
    if t.name=="template":
        newfname = dirname+"/"+t["name"]+ext
        f = open(newfname,"w")
        # note f.write(t) fails as t is not a string -- prettify works
        f.write(t.prettify())
        f.close()

不良行为:

{{ > directive }} 变为 {{ > directive }} 但需要保留为 {{ > directive }}

更新:f.write(t.prettify(formatter=None)) 有时会保留 >,有时会将其更改为 >。这似乎是最明显的变化,不知道为什么它会改变一些> 而不是其他的。

已解决:感谢 Hai Vu 和 https://stackoverflow.com/a/663128/103081

    import HTMLParser
    U = HTMLParser.HTMLParser().unescape
    soup = bs4.BeautifulSoup(open(filename,"r"))
    for t in soup.children:
        if t.name=="template":
            newfname = dirname+"/"+t["name"]+ext
            f = open(newfname,"w")
            f.write(U(t.prettify(formatter=None)))
            f.close()

另请参阅:https://gist.github.com/DrPaulBrewer/9104465

【问题讨论】:

    标签: python beautifulsoup handlebars.js


    【解决方案1】:

    您需要取消转义 HTML 内容。为此,请使用 HTMLParser 模块。这不是我最初的想法。我取自:

    How can I change '>' to '>' and '>' to '>'?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2013-03-21
      • 2019-05-08
      • 2017-12-23
      相关资源
      最近更新 更多