我正在尝试使用python中https://neweden-dev.com/ZKillboard_API的API。
我的代码到此为止:
import xml.etree.ElementTree as ET
import urllib2
import gzip
import zlib
url = 'https://zkillboard.com/api/kills/characterID/95089021/xml/'
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip,deflate')
data = urllib2.urlopen(request)
在此之后,我感到很困惑。
contents = data.read()
f = open("export.xml","w")
f.write(contents)
f.close()
以上是我的第一步。打开文件让我意识到它被压缩了(呃)。
所以从这一刻起我尝试了两件事:
f = open("test.xml.gz", "w")
f.write(data.read())
f.close()
g = gzip.open("test.xml.gz", "rb")
file_content = g.read()
g.close()
给了我错误:
Traceback (most recent call last):
File "C:\Users\[filepath]", line 19, in <module>
file_content = g.read()
File "C:\Python27\lib\gzip.py", line 254, in read
self._read(readsize)
File "C:\Python27\lib\gzip.py", line 312, in _read
uncompress = self.decompress.decompress(buf)
error: Error -3 while decompressing: invalid distance too far back
我的下一步是使用zlib:
x = zlib.decompress(data.read())
给了我错误:
Traceback (most recent call last):
File "C:\Users\[filepath]", line 15, in <module>
x = zlib.decompress(data.read())
error: Error -3 while decompressing data: incorrect header check
我知道我在这里缺少一些超级简单的东西,有什么想法吗?感谢。