【问题标题】:How to add extracted html in yattag?如何在 yattag 中添加提取的 html?
【发布时间】:2019-05-06 05:48:51
【问题描述】:

我正在尝试通过 yattag 创建 html。唯一的问题是,我从另一个 html 文件中使用的头文件,所以我读取了该文件并尝试将其插入为头文件。这是问题所在。虽然我传递了未转义的 html 字符串,但 yattag 将其转义。也就是说,它在添加到 html 字符串时将 '<。

MWE:

from yattag import Doc, indent
import html 
doc, tag, text = Doc().tagtext()


h = open(nbheader_template, 'r')
h_content= h.read()
h_content = html.unescape(h_content)

doc.asis('<!DOCTYPE html>')
with tag('html'):

    # insert dummy head
    with tag('head'):
        text(h_content)  # just some dummy text to replace later - workaround for now

    with tag('body'):
        # insert as many divs as no of files
        for i in range(counter):
            with tag('div', id = 'divID_'+ str(1)):
                text('Div Page: ' + str(i))

result = indent(doc.getvalue())



# inject raw head - dirty workaround as yattag not doing it
# result = result.replace('<head>headtext</head>',h_content)

with open('test.html', "w") as file:
    file.write(result)

输出:

上下文:我正在尝试将多个 jupyter python 笔记本合并到一个 html 中,这就是为什么重头。可以在here找到标头内容(nbheader_template)

【问题讨论】:

    标签: python html python-3.x beautifulsoup yattag


    【解决方案1】:

    如果你想防止转义,你必须使用doc.asis 而不是text

    asis 方法将一个字符串附加到文档中,没有任何形式的转义。

    另请参阅documentation

    【讨论】:

      【解决方案2】:

      我对“yattag”并不完全流利,但我发现缺少的一件事是:

       with tag('body'):
      

      您引用的代码(上面)将&lt;div&gt; 和文本放入您的标题中,它显然不属于。

      【讨论】:

      • 我刚刚测试了更新的代码,但结果相同。文本函数将箭头替换为 '<'不过还是一样的。
      • 这是 yattag 中的预期行为。显示 HTML 时,它将正确显示。这些物品应该是可以互换的。 '&=& =>'您唯一的其他(在 yattag 中)将像使用 DOCTYPE 标签一样使用“doc.asis()”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      相关资源
      最近更新 更多