首页 > 解决方案 > 将 utf-8 xml 保存到文件不会显示在浏览器中

问题描述

在 python3 中,我从网上下载了一个 xml 文件 https://cds.cern.ch/record/1642553?&of=xm&ot=245下载一个 xml 文件, 然后尝试保存它。

如果我在浏览器上打开 URL,我会得到(在两行之间): W± boson in pp collisions at √s = 7 TeV

如果我在我的电脑上打开文件,它会显示:W± boson in pp collisions at âs = 7 TeV

b'string 输出:W\xc3\x82\xc2\xb1 boson in pp 碰撞,\xc3\xa2\xc2\x88\xc2\x9as = 7 TeV

import requests
import codecs

cdsUrl = 'https://cds.cern.ch/record/1642553?&of=xm&ot=245'
cdsXml = requests.get(cdsUrl)

f = codecs.open("output.txt", "w", "utf-8-sig")
f.write(cdsXml.text)
f.close()

我试图能够读取文件并像浏览器一样正确显示内容。

标签: pythonxmlunicode

解决方案


似乎服务器发送的信息表明它将发送编码的数据ISO-8859-1

 print(cdsXml.encoding)

但它发送编码的数据utf-8- 但requests用于ISO-8859-1对其进行编码。

但是,如果您使用手动对其进行编码,utf-8那么您将获得正确的字符。

 print( cdsXml.content.decode('utf-8') )

代码:

import requests
import codecs

cdsUrl = 'https://cds.cern.ch/record/1642553?&of=xm&ot=245'
cdsXml = requests.get(cdsUrl)

print(cdsXml.encoding)

text = cdsXml.content.decode('utf-8')

f = codecs.open("output.txt", "w", "utf-8-sig")
f.write(text)

f.close()

推荐阅读