【问题标题】:Getting Non ascii characters as response from python urllib从 python urllib 获取非 ascii 字符作为响应
【发布时间】:2018-07-02 13:17:04
【问题描述】:
import urllib
from urllib.request import urlopen
import xml.etree.ElementTree as etree
response = urllib.request.urlopen("http://regnskaber.virk.dk/32673592/eGJybHN0b3JlOi8vWC1GNzY5MUY0Ny0yMDE0MDMyOV8xMzQxNThfMTc5L3hicmw.xml")

print (response.getcode())

print (response.readline()) # it gets the first line if you need to the check the output

请帮助解决这个编码问题。我需要解析 XML 内容。

【问题讨论】:

  • @haspander-它不是一体成型的。我在安装或使用这些库时有一些限制。
  • @ 9769953 - 输出为:b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00\xed=\xd9r\x1b9\x92\xef\x1d \xd1\xffP\xeb\x87\x8d\x99\x08\x89\xe2}x=\x8a\x95,\xb9\xc7\xdb\xb6\xe5\xb04\x9e\xddG\x90\x05\x920\x8bU \x1c\x00\xa4\xc5\x0f\xd8Oi\x7f\x83\xdf\xf9c\x9b\x99@\xdd\x07\x8b\x94\xdcR\xefL\x84\xc3\x92X@"\xef\x0b@ \xf1\xd5\xfdXz\xe2%\xfe\xef\xdc/=_\xfd\xe5\xc5\\\xeb\xd5\xcb\xb3\xb3\xaf_\xbf6\xf0\xe3F gg\xedf\xb3s&| \xa5\x99?\xe1/\xcc\xc8\x97\xd3h,\x8ds\'\x13\xd6p\x17g*\x18\x87#\xc6\xc5#\xb8\xaf\xe5\xf6\x92y\x08 \xecv\xce\xb9\xbe\x98L\x82\xb5\xaf\xdf\x04r\xf9\xd6\x9f\x04K
  • 这不是正确的,我需要 XML 来解析
  • 在您的问题中添加额外/新信息,而不是作为评论(不需要 cmets)。回溯也很有用。但请参阅我的其他评论和我的回答。

标签: python python-3.x urllib


【解决方案1】:

响应开头的魔术字节0x1f8b 表示zlib 压缩。服务器通常会压缩数据以进行传输,而浏览器会自动解压缩它们。在这里,您必须自己完成第二步:

import urllib
from urllib.request import urlopen
import xml.etree.ElementTree as ET
from io import BytesIO
import gzip
response = urllib.request.urlopen("http://regnskaber.virk.dk/32673592/eGJybHN0b3JlOi8vWC1GNzY5MUY0Ny0yMDE0MDMyOV8xMzQxNThfMT\
c5L3hicmw.xml")
print (response.getcode())

data = response.read()

compdata = BytesIO(data)
text = []
for unit in gzip.GzipFile(fileobj=compdata):
    text.append(unit)
text = b"".join(text)

tree = ET.fromstring(text)
print(tree)

输出:

200
<Element '{http://www.xbrl.org/2003/instance}xbrl' at 0x104d09098>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2021-06-01
    • 1970-01-01
    相关资源
    最近更新 更多