我的使用情景:
因為要從官網上下載CNF文件做測試,但是官網里每一個URL對應一個CNF文件,總共400個文件,肯定不能手動下載。
步驟:
1、首先將所有URL保存到一個.txt內,如圖所示。
2、python代碼如下
# -- coding:UTF-8 --<code> import requests import re from io import BytesIO file = open("E:/cnf/test.txt") # 打開存放鏈接的TXT文檔 num = 0 while 1: line = file.readline() # 逐行讀鏈接 if not line: break print("正在下載 第 %d cnf...." % num) num += 1 image_url = line ima = image_url.replace('\n','') #去除每行的'\n',不然會404 try: requests.packages.urllib3.disable_warnings() r = requests.get(ima, verify=False) # 創建響應對象 path = re.sub("https://gbd.iti.kit.edu/file/", "E:/cnf/", line) # 通過re模塊的搜索和替換功能,生成下載文檔的保存地址 path = re.sub('\n', '', path + ".cnf.zip") # 刪除path末尾的換行符'\n' f = open(path, "wb") f.write(r.content) # 將響應對象的內容寫下來 f.close() except Exception as e: print('無法下載,%s' % e) continue file.close()
3、運行即可,會保存成如下形式
4、缺點
(1)缺少進度條和下載速度的顯示
(2)如果由於種種原因下載失敗了,會停止,跑了一晚上還在原地杵。
5、其他解決方法
使用Linux里的wget會更好用,其中.uri文件發揮.txt文件的作用
wget --content-disposition -i sc2020-main.uri