日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python?如何使用requests下載文件_python

作者:阿宅gogo ? 更新時間: 2022-04-18 編程語言

使用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查看到,需要使用抓包工具獲取

用requests.get下載文件

不知道大家有沒有遇到這樣的問題

就是url源不穩定,時不時下載到空文件,我終于想到了一個解決的好辦法,分享給大家。

def downloadfile(url,filename=None):
  if(not filename):							#如果參數沒有指定文件名
    filename=os.path.basename(url)			#取用url的尾巴為文件名
  leng=1
  while(leng==1):
    torrent=requests.get(url,headers=headers)
    leng=len(list(torrent.iter_content(1024)))  #下載區塊數
    if(leng==1):								#如果是1 就是空文件 重新下載
      print(filename,'下載失敗,重新下載')
      sleep(1)
    else:
      print(path,'下載完成')
  with open(filename,'wb') as f:				
    for chunk in torrent.iter_content(1024):	#防止文件過大,以1024為單位一段段寫入
      f.write(chunk)

原文鏈接:https://www.cnblogs.com/wbw-test/p/11984382.html

欄目分類
最近更新