python - 将 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()
我试图能够读取文件并像浏览器一样正确显示内容。
解决方案
似乎服务器发送的信息表明它将发送编码的数据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()
推荐阅读
- arrays - 如何使用php的strpos函数从数组中统计相似的单词?
- json - 使用 Powershell 将文件的内容转换为可以使用 JSON 传输的字符串
- reactjs - Why does my NavLink's doesn't set to active using Semantic-ui-react?
- javascript - 如何使用 vuex 删除项目?
- debugging - 如何强制调试跟踪语句按顺序评估?
- gradle - 如何通过 LibGDX (Gradle) 导入和使用 JsInterop?
- c# - 在 SQL 查询中传递 DECLARE 参数
- node.js - ListItemText 不显示数据
- javascript - Javascript:如何从“动态”创建的复选框中获取值
- c++ - 如何实现 std::atomic 引用计数器?