zoukankan      html  css  js  c++  java
  • python 使用requests下载文件

    1、获取token,或者session(如不需要可忽略)

    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、获取下载路径(如果请求后直接返回文件内容,可直接进行第三步)

    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、根据下载路径拼接下载url,完成文件下载以及写入

    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)

     备注:

      第二步返回json数据,包含路径、文件名,实际是文件生成过程,第三步下载在服务端生成的文件,有时第三步无法在页面F12查看到,需要使用抓包工具获取

  • 相关阅读:
    python3(二十七)property
    python3(二十六)slots
    python3(二十五) getClassInfo
    python3(二十四) subClas
    python3(二十三)classInstance
    python3(二十二) oop
    python3(二十一) pip
    python3(二十) module
    python3(十九)Partial func
    python3(十八)decorator
  • 原文地址:https://www.cnblogs.com/wbw-test/p/11984382.html
Copyright © 2011-2022 走看看