Python實(shí)現(xiàn)批量下載文件的代碼詳解
概述
該工具是一個用 Python 編寫的批量下載文件腳本。它從配置文件中讀取下載任務(wù)列表,并并行下載文件,同時顯示下載進(jìn)度。該工具使用 requests 庫進(jìn)行 HTTP 請求,使用 tqdm 庫顯示下載進(jìn)度,并使用 configparser 庫讀取配置文件。
依賴
在使用該工具之前,請確保已安裝以下庫:
requeststqdm
可以使用以下命令安裝所需的庫:
pip install requests tqdm
配置文件
創(chuàng)建一個配置文件(例如 downloads.ini),其中包含下載任務(wù)列表。配置文件使用 INI 格式,每個下載任務(wù)有一個單獨(dú)的節(jié),每個節(jié)包含 url 和 path 兩個字段。
示例配置文件 downloads.ini:
[file1] url = http://example.com/file1.jpg path = downloads/file1.jpg [file2] url = http://example.com/file2.jpg path = downloads/file2.jpg [file3] url = http://example.com/file3.jpg path = downloads/file3.jpg
運(yùn)行腳本
將以下代碼保存為 batch_download.py:
import os
import requests
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
import configparser
import argparse
def download_file(task):
"""
下載單個文件并保存到指定路徑,并顯示下載進(jìn)度
"""
url = task['url']
path = task['path']
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with requests.get(url, stream=True) as r:
r.raise_for_status()
total_size = int(r.headers.get('content-length', 0))
with open(path, 'wb') as f, tqdm(
total=total_size, unit='B', unit_scale=True, desc=os.path.basename(path)
) as pbar:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
pbar.update(len(chunk))
print(f'{path} 下載完成')
except Exception as e:
print(f'下載 {url} 失敗: {e}')
def read_config(config_path):
"""
從配置文件讀取下載任務(wù)列表
"""
config = configparser.ConfigParser()
config.read(config_path)
tasks = []
for section in config.sections():
url = config[section]['url']
path = config[section]['path']
tasks.append({'url': url, 'path': path})
return tasks
def main(config_path):
"""
主函數(shù),讀取配置文件并并行下載文件
"""
tasks = read_config(config_path)
with ThreadPoolExecutor(max_workers=5) as executor:
executor.map(download_file, tasks)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='批量下載文件工具')
parser.add_argument('config', type=str, help='配置文件路徑')
args = parser.parse_args()
main(args.config)
使用方法
創(chuàng)建配置文件:按照上述示例創(chuàng)建
downloads.ini文件,并根據(jù)需要修改下載任務(wù)。運(yùn)行腳本:在命令行中運(yùn)行以下命令,指定配置文件路徑:
python batch_download.py downloads.ini
代碼功能說明
- 導(dǎo)入庫
import os import requests from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import configparser import argparse
download_file函數(shù):下載單個文件并保存到指定路徑,同時顯示下載進(jìn)度。
def download_file(task):
url = task['url']
path = task['path']
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with requests.get(url, stream=True) as r:
r.raise_for_status()
total_size = int(r.headers.get('content-length', 0))
with open(path, 'wb') as f, tqdm(
total=total_size, unit='B', unit_scale=True, desc=os.path.basename(path)
) as pbar:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
pbar.update(len(chunk))
print(f'{path} 下載完成')
except Exception as e:
print(f'下載 {url} 失敗: {e}')
read_config函數(shù):從配置文件讀取下載任務(wù)列表。
def read_config(config_path):
config = configparser.ConfigParser()
config.read(config_path)
tasks = []
for section in config.sections():
url = config[section]['url']
path = config[section]['path']
tasks.append({'url': url, 'path': path})
return tasks
main函數(shù):讀取配置文件并并行下載文件。
def main(config_path):
tasks = read_config(config_path)
with ThreadPoolExecutor(max_workers=5) as executor:
executor.map(download_file, tasks)
- 命令行參數(shù)解析:使用
argparse解析命令行參數(shù),指定配置文件路徑。
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='批量下載文件工具')
parser.add_argument('config', type=str, help='配置文件路徑')
args = parser.parse_args()
main(args.config)
注意事項(xiàng)
- 請確保配置文件中的 URL 是有效的下載鏈接。
- 如果下載過程中出現(xiàn)錯誤,腳本會輸出相應(yīng)的錯誤信息。
到此這篇關(guān)于Python實(shí)現(xiàn)批量下載文件的代碼詳解的文章就介紹到這了,更多相關(guān)Python批量下載文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python調(diào)用Pandas實(shí)現(xiàn)Excel讀取
這篇文章主要為大家介紹了在Python中如何調(diào)用Pandas實(shí)現(xiàn)Excel文件的讀取,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-04-04
python中視頻音頻的剪輯與處理實(shí)現(xiàn)
Python中輕松實(shí)現(xiàn)各種視頻處理操作,包括剪輯、合并、添加音頻、文本、特效等多種功能,主要介紹了python中視頻音頻的剪輯與處理實(shí)現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-06-06
Keras實(shí)現(xiàn)Vision?Transformer?VIT模型示例詳解
這篇文章主要為大家介紹了Keras實(shí)現(xiàn)Vision?Transformer?VIT模型示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
使用Python實(shí)現(xiàn)惰性加載的三種方法詳解
在現(xiàn)代軟件開發(fā)中,惰性加載是一種優(yōu)化技術(shù),用于延遲計算或加載資源密集型屬性,直至首次訪問時才執(zhí)行,Python提供了豐富的元類與屬性操作機(jī)制,允許我們通過getattr、getattribute和setattr方法實(shí)現(xiàn)惰性屬性管理,本文將詳細(xì)探討這三種方法的實(shí)現(xiàn)細(xì)節(jié),需要的朋友可以參考下2025-10-10

