Python 将请求的响应保存到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31126596/
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
Saving response from Requests to file
提问by Chris J. Vargo
I'm using Requeststo upload a PDF to an API. It is stored as "response" below. I'm trying to write that out to Excel.
我正在使用请求将 PDF 上传到 API。它在下面存储为“响应”。我正在尝试将其写出到 Excel。
import requests
files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "w")
file.write(response)
file.close()
I'm getting the error:
我收到错误:
file.write(response)
TypeError: expected a character buffer object
采纳答案by Sait
As Peteralready pointed out:
正如彼得已经指出的那样:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
您可能还想检查r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
另外:https: //2.python-requests.org/en/latest/user/quickstart/
回答by bhawnesh dipu
You can use the response.text
to write to a file:
您可以使用response.text
写入文件:
import requests
files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()