首页 > 解决方案 > 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.

Snapshot of the form data

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

标签: pythonrestpost

解决方案


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)

请求文件


推荐阅读