Skip to main content
 首页 » 编程设计

python之尝试在 python 中解码 HTTP 响应。无法弄清楚JSON解码

2024年11月24日9yxwkf

这是基本请求:

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) 

这是 header ,我可以看到它是 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 

我做错了什么?

请您参考如下方法:

正如响应 header 所暗示的,数据已使用 gzip 压缩。在执行任何其他操作之前,您需要解压缩它。

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