我正在使用Requests上传一个PDF到一个应用程序接口。它被存储为下面的"response“。我正试着把它写到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()我得到了一个错误:
file.write(response)
TypeError: expected a character buffer object发布于 2015-06-30 06:39:20
正如Peter已经指出的:
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您可能还想检查r.text。
发布于 2018-09-10 13:17:45
您可以使用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
with open("resp_text.txt", "w") as file:
file.write(response.text)发布于 2021-01-09 06:24:03
我相信所有现有的答案都有相关的资料,但我想总结一下。
由requests get和post操作返回的响应对象包含两个有用的属性:
响应属性
response.text -包含具有响应text.response.content的str -包含具有原始响应内容的bytes。您应该根据您期望的响应类型选择这些属性中的一个或另一个。
对于基于文本的响应(html、json、yaml等),您可以使用response.text
response.content.正在将响应写入文件
在向文件写入响应时,您需要使用具有适当文件写入模式的open function。
"w" -普通写入模式。"wb" -二进制写入模式。示例
文本请求和保存
# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
f.write(response.text)二进制请求和保存
# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
f.write(response.content)回答原来的问题
原始代码应该可以通过使用wb和response.content来工作
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", "wb")
file.write(response.content)
file.close()但我会走得更远,使用with context manager for open。
import requests
with open('1.pdf', 'rb') as file:
files = {'f': ('1.pdf', file)}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
with open("out.xls", "wb") as file:
file.write(response.content)https://stackoverflow.com/questions/31126596
复制相似问题