requests to download files using python

1, access token, or a session (ignored if not required)

login_url = "http://xxxx/api/auth/login"
login_data = {"username":"test3","password":"123456"}
login_res = requests.post(url=login_url,data = login_data)
token = login_res.json()["data"]["token"]

2, obtaining the download path (if the request directly returns the file contents, the third step can directly)

batch_url = "http://xxxx/api/models/batch"
batch_data = {"ids":"[4]","version_number":"[309]"}
headers = {"Authorization":"bearer %s" % token}
batch_res = requests.get(url=batch_url,params=batch_data,headers=headers)

3. The download path splicing download url, download and complete the file write

file_path = batch_res.json()['data']['file_path']
file_name = batch_res.json()['data']['file_name']

down_url = "http://xxxx/api/report/down"
down_data = {"type":2,
             "file_path":file_path,
             "file_name":file_name,
             "token":token
             }

down_res = requests.get(url=down_url,params=down_data)

with open(file_name,"wb") as code:
    code.write(down_res.content)

 Remarks:

  The second step is returned json data, include the path, file name, file generation process is actually the third step to download files on the server generated the third step sometimes can not see the page F12, require the use of packets captured

Guess you like

Origin www.cnblogs.com/wbw-test/p/11984382.html