我相信所有现有的答案都包含相关信息,但我想总结一下。
返回的响应对象requests
get 和 post 操作包含两个有用的属性:
响应属性
-
response.text
- 包含str
与响应文本。
-
response.content
- 包含bytes
与raw响应内容。
您应该根据您期望的响应类型选择这些属性中的一个或另一个。
- 对于基于文本的响应(html、json、yaml 等),您可以使用
response.text
- 对于基于二进制的响应(jpg、png、zip、xls 等),您可以使用
response.content
.
将响应写入文件
将响应写入文件时,您需要使用开放功能 https://docs.python.org/3/library/functions.html?highlight=open#open使用适当的文件写入模式。
- 对于文本回复,您需要使用
"w"
- 纯写模式。
- 对于二进制响应,您需要使用
"wb"
- 二进制写入模式。
Examples
文本请求并保存
# 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
and 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
上下文管理器open https://book.pythontips.com/en/latest/context_managers.html.
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)