Python HTML重音标记问题与Yattag、dominate

Python HTML重音标记问题与Yattag、dominate,python,html,encoding,dominate,yattag,Python,Html,Encoding,Dominate,Yattag,希望我能在这里找到一些答案。我正在尝试用Python3编写html。 我尝试过yattag和dominate模块,但两者都有相同的问题:当我尝试将代码内容写入HTML文件时,生成的文档不会显示带重音符号的字母,而是显示一个带问号的黑色小数字。(见下图) 我的代码看起来像这样 使用支配: import dominate import dominate.tags as tg #an example doc _html = tg.html(lang='es') _head = _html.add(tg

希望我能在这里找到一些答案。我正在尝试用Python3编写html。 我尝试过yattag和dominate模块,但两者都有相同的问题:当我尝试将代码内容写入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())
因此,当我在这两种情况下更改或删除字符集时,问题似乎消失了。 我用最后两行来写简单的文档,我想每个人都是这样做的,重音符号没有问题。 问题似乎是导入的模块如何管理字符集以显示页面内容。我不知道。你知道有什么办法避开这件事吗? 希望你做得很好。多谢各位


您可以在编辑文件时使用
编码
参数:

with open("document2.html", 'w', encoding='utf-8') as file:
专业提示:您可以使用
errors
参数定义发生错误时的行为:

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