我正在使用python3.4。
当我在utf-8文件上使用urllib.request.urlretrieve(link, filename="file.html")
时,生成的file.html没有被正确编码。如何确保文件是使用utf-8编码的?在这种情况下,如何实现.decode(utf-8)?
编辑
这是页面的原始部分:
peuple,mon,je parle; 莫伊,迪欧,吉苏斯·迪厄! 指责帕斯献祭; tes holocaustes sont toujours devant moi. Je ne prendrai pas un seul taureau de ton domaine, pas un bélier de tes的附件。 关于m‘’appartient的Tout le gibier des 这是一个很好的例子。斯杰·法伊姆,伊拉杰·莱德雷? 这是一种财富。 威斯-杰马格里拉椅 et boire le sang des béliers?‘as tuàréciter mes lois, 拉布切联盟, toi qui n‘’aimes是责备 等等,腰部?
这就是我在保存的文件中得到的:
��coute,mon,je parle ;� Moi,Dieu,je suis ton Dieu !� 指责帕斯献祭; ��Je ne prendrai pas un seul taureau de ton domaine, pas un b�lier de tes附件.� 用于�s m‘’appartient的Tout le gibier des et le b b�tail des hauts p�turage�Si‘Si,irai-je te le胆? �. 威斯-杰马格里拉椅 �liers ?��Qu‘’as tu�r�citer mes lois,� �garder�la bouche,� toi qui n‘’aimes是责备 ��
我注意到,在页面的某些部分,重音字符实际上并不是utf-8编码的,但是浏览器正确地显示了它。例如,不是É
,而是É
,当下载该文件时,这似乎会导致问题。
发布于 2014-06-28 10:05:51
您可以使用显示这里的方法逐行取消转义文件中的HTML转义序列。
import html.parser
h = html.parser.HTMLParser()
with urllib.request.urlopen(link) as fin, open(
"file.html", 'w', encoding='utf-8') as fout:
for line in fin:
fout.write(h.unescape(line.decode('utf-8')))
发布于 2014-06-28 10:30:31
我建议您使用它来处理这个问题:它将加载的文档隐含地转换为utf-8。
markup = "<h1>Sacr\xc3\xa9 bleu!</h1>"
soup = BeautifulSoup(markup)
soup.h1
# <h1>Sacré bleu!</h1>
soup.h1.string
# u'Sacr\xe9 bleu!'
BeautifulSoup文档:这里
https://stackoverflow.com/questions/24465128
复制相似问题