无法解码Python Web请求。

33

我正在尝试向我的交易账户发起网络请求。Python无法解码网络请求。网络请求成功,状态码为200。

以下是代码:

import requests

headers = {
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    'x-kite-version': '1.2.1',
    'accept': 'application/json, text/plain, */*',
    'referer': 'https://kite.zerodha.com/orders',
    'authority': 'kite.zerodha.com',
    'cookie': '__cfduid=db8fb54c76c53442fb672dee32ed58aeb1521962031; _ga=GA1.2.1516103745.1522000590; _gid=GA1.2.581693731.1522462921; kfsession=CfawFIZq2T6SghlCd8FZegqFjNIKCYuO; public_token=7FyfBbbxhiRRUso3425TViK2VmVszMCK; user_id=XE4670',
    'x-csrftoken': '7FyfBbbxhiRRUso3425TViK2VmVszMCK',
}

response = requests.get('https://kite.zerodha.com/api/orders', headers=headers)


x=str(response.content.decode("utf-8") )
Sorry, I cannot translate the garbled text as it appears to be encoded or encrypted and does not contain any understandable content. The message in the second paragraph indicates that various attempts have been made to decode the text but have been unsuccessful.
3个回答

42
根据你提供的代码中未包含的response.headers(但可以通过运行你的代码轻松获取),响应是使用Brotli压缩Content-Encoding': 'br')进行编码的。你可以使用brotlipy对其进行解压缩:
import brotli
brotli.decompress(response.content)
#b'{"status":"success","data":[{"placed_by":"XE4670","order_id":"180331000000385",  
#"exchange_order_id":null,"parent_order_id":null,"status":"REJECTED",
#"status_message":"ADAPTER is down","order_timestamp":"2018-03-31 07:59:42", 
#"exchange_update_timestamp":null,...}

现在,如承诺一样,它是JSON格式的('Content-Type': 'application/json')。


抱歉挖掘这篇文章,但当我使用brotly.decompress(response.content)时,我遇到了brotli.brotli.Error: Decompression error: b'PADDING_2',我做错了什么? - robinvrd
2
使用brotli代替brotlipy。它由Google更频繁地更新和维护。 - Dipu
抱歉,我有一个问题。使用brotli.decompress(response.content)时会引发错误。 https://dev59.com/Fb3pa4cB1Zd3GeqPYykw - xin.chen
1
如我在上面的问题中所提到的,一旦安装了brotli,requests会自动处理它。您无需手动调用decompresss函数。 - Laurent Pinson

19

如果服务器只返回brotli压缩响应,则需要对响应进行解压缩,然后才能使用。

幸运的是,自从v2.26.0更新以来,请求库支持Brotli压缩,如果安装了brotlibrotlicffi包。因此,如果响应编码为br,请求库将自动处理并解压缩它。

首先;

pip install brotli,

然后;

import requests

r = requests.get('some_url')
r.json()

6

我通过更改请求头来解决了这个问题,

headers = {
    'accept-encoding': 'gzip, deflate, br',
    ...}

to

headers = {
    'accept-encoding': 'gzip, deflate, utf-8',
    ...}


2
如果API支持直接导出为utf-8,这可能有效,但在我看来不能作为一般解决方案。 - Felício
3
我同意,但值得一试。 - basic mojo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接