如何使用 Python 在请求中获取响应的原始内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16923898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the raw content of a response in requests with Python?
提问by Juan Carlos Coto
Trying to get the raw data of the HTTP response content in requestsin Python. I am interested in forwarding the response through another channel, which means that ideally the content should be as pristine as possible.
尝试requests在 Python 中获取 HTTP 响应内容的原始数据。我有兴趣通过另一个渠道转发响应,这意味着理想情况下,内容应尽可能原始。
What would be a good way to do this?
这样做的好方法是什么?
采纳答案by Brien
If you are using a requests.getcall to obtain your HTTP response, you can use the rawattribute of the response. Here is the code from the requestsdocs.
如果您使用requests.get调用来获取 HTTP 响应,则可以使用raw响应的属性。这是requests文档中的代码。
>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
回答by Tom
After requests.get(), you can use r.contentto extract the raw Byte-type content.
之后requests.get(),您可以使用它r.content来提取原始 Byte 类型的内容。
r = requests.get('https://yourweb.com', stream=True)
r.content

