希望我能在这里找到一些答案。我试着用python 3来写html,我试过yattag和dominate模块,但是我遇到了同样的问题:当我试图把代码的内容写到一个HTML文件中时,生成的文档不会显示带有重音符号的字母,而是会显示一个黑色的小问号。(见下图)
我的代码如下所示。
使用dominate:
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())因此,当我在这两种情况下更改或删除字符集时,问题似乎都消失了。我使用最后两行来编写简单的文档,我猜每个人都是这样做的,而且重音符号没有问题。问题似乎是导入的模块如何管理字符集来显示页面内容。我不知道。你知道有什么方法可以解决这个问题吗?希望你一切顺利。谢谢。

发布于 2020-07-16 09:23:09
您可以在open文件时使用encoding参数:
with open("document2.html", 'w', encoding='utf-8') as file:Pro提示:您可以使用errors参数定义出错时的行为:
with open("document2.html", 'w', encoding='utf-8', errors='ignore') as file:https://stackoverflow.com/questions/62925017
复制相似问题