我相信所有现有的答案都包含相关信息,但我想总结一下。
requests get 和 post 操作返回的响应对象包含两个有用的属性:
响应属性
-
response.text - 包含 str 和响应文本。
-
response.content - 包含带有原始响应内容的bytes。
您应该根据您期望的响应类型选择这些属性中的一个或其他。
- 对于基于文本的响应(html、json、yaml 等),您可以使用
response.text
- 对于基于二进制的响应(jpg、png、zip、xls 等),您可以使用
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()
但我会更进一步,使用withcontext 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)