Python3 使用requests请求,解码时出错:'utf8' codec can't decode byte 0x8b in position 1: invalid start byte

requests请求的响应内容能够通过几个属性获得:

response.text  

为解码之后的内容,解码会根据响应的HTTP Header中的Content-Type选择字符集。例如

"'Content-Type': 'text/html;charset=UTF-8'"

就会使用“UTF-8”解码。可通过访问response.encoding获得当前使用的字符集。

也可修改使用的字符集:

response.encoding = 'GBK'

这样再次调用response.text的时候,会返回GBK解码的内容。

response.content

为二进制内容,并且已经自动对传输中使用的gzip和deflate编码进行了解码。

response.raw

为原始的响应内容,可以用来做一些分析。只是需要在初始化的时候加上参数stream=True,不然获取到的值为b''。但需要注意的是,添加参数(stream=True)之后,text和content都不能使用了。。。都会报错:

requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(53 bytes read)', IncompleteRead(53 bytes read))

response.json()

这一般用于已知返回数据格式为JSON字符串的情况。如果返回的是不可用的JSON数据会抛出异常:

ValueError: No JSON object could be decoded

回到遇到的问题上来:

'utf8' codec can't decode byte 0x8b in position 1: invalid start byte

该问题发生在调用response.content.decode()时。

解决办法:

  1. 去掉请求HTTP Header中的gzip:

"Accept-Encoding":"gzip, deflate, sdch, br",

  2. 对原始内容进行gzip解压处理

    

原文地址:https://www.cnblogs.com/xzysaber/p/6491886.html