【问题标题】:Python HTML Accent mark issues with Yattag, dominateYattag的Python HTML Accent标记问题,占主导地位
【发布时间】:2020-07-15 23:05:08
【问题描述】:

希望我能在这里找到一些答案。我正在尝试用 python 3 编写 html。 我尝试过 yattag 和主控模块,但两者都有相同的问题:当我尝试将代码的内容写入 HTML 文件时,生成的文档不显示带重音符号的字母,而是显示一个问号显示黑色小图。 (见下图)

我的代码如下所示。

使用支配:

import dominate
import dominate.tags as tg
#an example doc
_html = tg.html(lang='es')
_head = _html.add(tg.head())
_body = _html.add(tg.body())
with _head:
    tg.meta(charset="UTF-8") #this line seems to be the problem
with _body:
    tg.p("Benjamín")
print(_html)
#when I print to console, the accent mark in the letter 'í' is there but...
#when I write the file, the weird character is displayed 

with open("document.html", 'w') as file:
    file.write(_html.render())

使用 yattag 也是一样

from yattag import Doc
#another example doc
doc, tag, text = Doc().tagtext()
with tag("html", "lang='es'"):
    with tag("head"):
        doc.stag("meta", charset="UTF-8") #this line seems to be the problem
    with tag("body"):
        text("Benjamín")
#when I print to console, the accent mark in the letter 'í' is there but...
#when I write the file, the weird character is displayed 
with open("document2.html", 'w') as file:
    file.write(doc.getvalue())

因此,当我在这两种情况下更改或删除字符集时,问题似乎就消失了。 我使用最后两行来编写简单的文档,我猜每个人都这样做,并且重音符号没有问题。 问题似乎是导入的模块如何管理字符集以显示页面内容。嗯,我不知道。你知道有什么办法可以解决这个问题吗? 希望你一切都好。谢谢。

【问题讨论】:

    标签: python html encoding dominate yattag


    【解决方案1】:

    open文件时可以使用encoding参数:

    with open("document2.html", 'w', encoding='utf-8') as file:
    

    专业提示:您可以使用errors 参数定义出现错误时的行为:

    with open("document2.html", 'w', encoding='utf-8', errors='ignore') as file:
    

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 2016-04-18
      • 2012-06-07
      • 1970-01-01
      • 2017-08-08
      • 2013-02-13
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多