python - Send POST request with Python that generates a download and download the file
问题描述
There's a website that has a button which downloads an Excel file. After I click, it takes around 20 seconds for the server API to generate the file and send it back to my browser for download.
If I monitor the communication after I click the button, I can see how the browser sends a POST request to a server with a series of headers and form values.
Is there a way that I can simulate a similar POST request programmatically using Python, and retrieve the Excel file after the server sends it over?
Thank you in advance
解决方案
requests 模块用于发送各种类型的请求。
requests.post
同步发送 post 请求。
可以使用 设置有效负载数据 可以使用data=
访问响应.content
。
请务必检查.status_code
并仅保存成功的响应代码
还要注意在 open 中使用“wb”,因为我们希望将文件保存为二进制文件而不是文本。
例子:
import requests
payload = {"dao":"SampleDAO",
"condigId": 1,
...}
r = requests.post("http://url.com/api", data=payload)
if r.status_code == 200:
with open("file.save","wb") as f:
f.write(r.content)
推荐阅读
- string - 从字符串中提取带引号的部分
- android - 重用 ViewPager 和 FragmentPagerAdapter 的片段
- python-docx - 将pptx幻灯片导入docx文档
- excel - 为什么 xlCalculationManual 会加快非依赖工作簿的速度?
- mysql - 将一列添加到具有更多结果行的联合选择语句结果
- php - 使用 TCPDF 转换灰度创建的 PDF 中的嵌入 SVG
- sql - SQL R 代码教程问题,从模型预测不会运行。反序列化错误
- c++ - 如何将 QPushButton 放入小部件中的 Qt3DWindow 中?
- java - 四舍五入到小数点后两位
- javascript - 使用 firebase 数据库时 this.setState 不起作用