从 python urllib 获取非 ascii 字符作为响应

Getting Non ascii characters as response from python urllib

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

请帮助解决此编码问题 problem.I 需要解析 XML 内容。

响应开头的魔法字节 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>