【问题标题】:Trying to decode HTTP Response in python. Can't figure out JSON decoding尝试在 python 中解码 HTTP 响应。无法弄清楚 JSON 解码
【发布时间】:2019-08-02 14:55:15
【问题描述】:

这是基本要求:

req = urllib2.Request(f"https://www.voter.ie/api/search/name/{name}/surname/{surname}/eircode/{eircode}/lang/en")

req.add_header("Connection", "keep-alive")
req.add_header("Accept", "application/json, text/plain, */*")
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 OPR/62.0.3331.99")
req.add_header("Accept-Encoding", "gzip, deflate, br")
req.add_header("Accept-Language", "en-US,en;q=0.9")

response = urllib2.urlopen(req)

这是标头,我可以看到它是 Content-Type 中的 JSON,编码是 utf-8

response.getheaders()

[('Transfer-Encoding', 'chunked'),
 ('Content-Type', 'application/json; charset=utf-8'),
 ('Content-Encoding', 'gzip'),
 ('Vary', 'Accept-Encoding'),
 ('Server', 'Kestrel'),
 ('Request-Context', 'appId=cid-v1:25017a8d-4490-471a-a8d0-e9e17860f987'),
 ('Strict-Transport-Security', 'max-age=2592000'),
 ('X-Content-Type-Options', 'nosniff'),
 ('Referrer-Policy', 'no-referrer'),
 ('X-XSS-Protection', '1; mode=block'),
 ('X-Frame-Options', 'Deny'),
 ('X-Powered-By', 'ASP.NET'),
 ('Date', 'Fri, 02 Aug 2019 14:45:33 GMT'),
 ('Connection', 'close')]

所以当我尝试阅读或解码时,我遇到了很多错误,但首先这就是它的样子。我没有发布完整的字符串,因为它太长了,但这是一个示例:

response.read()

b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07`\x1cI\x96%&/m\xca{\x7fJ\xf5J\xd7\xe0t\xa1\x08\x80`\x13$\xd8\x90@\x10\xec\xc1\x88\xcd\xe6\x92\xec\x1diG#)\xab*\x81\xcaeVe]f\x16@\xcc\xed\x9d\xbc\xf7\xde{\xef\xbd\xf7\xde{\xef\xbd\xf7\xba;\x9dN\'\xf7\xdf\xff?\\fd\x01l\xf6\xceJ\xda\xc9\x9e!\x80\xa

我尝试过使用在 StackOverflow 上找到的方法:

response.read().decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte


raw_data = response.read()
json.loads(raw_data.decode('utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte


string = response.read().decode('utf-8')
json_obj = json.loads(string)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

我做错了什么?

【问题讨论】:

    标签: python json encoding utf-8 gzip


    【解决方案1】:

    正如响应标头所示,数据已使用 gzip 压缩。您需要先解压缩它,然后再执行其他操作。

    import gzip, json
    gz = response.read()
    j = gzip.decompress(gz)
    data = json.loads(j.decode('utf-8')) 
    

    【讨论】:

    • 修复了它。非常感谢。以前没有遇到过压缩响应。现在我知道了。
    • 收到错误 AttributeError: 'module' object has no attribute 'decompress'
    • @Patlatus gzip.decompress 是在 Python 3.2 中添加的,因此如果您使用的是较早的 Python,则需要使用该版本中提供的工具(我现在没有时间调查恐怕)。
    猜你喜欢
    • 2012-11-26
    • 2021-04-08
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2018-07-23
    相关资源
    最近更新 更多