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解壓處理