将utf8xml保存到文件将不会显示在浏览器中

2024-09-29 19:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果我在浏览器上打开URL,我会得到(行间): W±玻色子在√s=7 TeV的pp碰撞中

如果我打开电脑上的文件,它会显示: πs=7tev时pp碰撞中的W±玻色子

字符串输出: W\xc3\x82\xc2\xb1玻色子在\xc3\xa2\xc2\x88\xc2\x9as=7tev的pp碰撞中

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()

我试图能够读取文件,并正确地显示浏览器的内容做。你知道吗


Tags: 文件ofhttpsimport浏览器otchrecord
1条回答
网友
1楼 · 发布于 2024-09-29 19:30:57

似乎服务器发送的信息将发送编码的数据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()

相关问题 更多 >

    热门问题