Python實現(xiàn)批量下載文件的代碼詳解
概述
該工具是一個用 Python 編寫的批量下載文件腳本。它從配置文件中讀取下載任務列表,并并行下載文件,同時顯示下載進度。該工具使用 requests 庫進行 HTTP 請求,使用 tqdm 庫顯示下載進度,并使用 configparser 庫讀取配置文件。
依賴
在使用該工具之前,請確保已安裝以下庫:
requeststqdm
可以使用以下命令安裝所需的庫:
pip install requests tqdm
配置文件
創(chuàng)建一個配置文件(例如 downloads.ini),其中包含下載任務列表。配置文件使用 INI 格式,每個下載任務有一個單獨的節(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
運行腳本
將以下代碼保存為 batch_download.py:
import os
import requests
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
import configparser
import argparse
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}')
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
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ù)需要修改下載任務。運行腳本:在命令行中運行以下命令,指定配置文件路徑:
python batch_download.py downloads.ini
代碼功能說明
- 導入庫
import os import requests from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import configparser import argparse
download_file函數(shù):下載單個文件并保存到指定路徑,同時顯示下載進度。
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ù):從配置文件讀取下載任務列表。
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)
注意事項
- 請確保配置文件中的 URL 是有效的下載鏈接。
- 如果下載過程中出現(xiàn)錯誤,腳本會輸出相應的錯誤信息。
到此這篇關(guān)于Python實現(xiàn)批量下載文件的代碼詳解的文章就介紹到這了,更多相關(guān)Python批量下載文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中的json數(shù)據(jù)和pyecharts模塊入門示例教程
JSON是一種輕量級的數(shù)據(jù)交互格式。可以按照.JSON指定的格式去組織和封裝數(shù)據(jù),這篇文章主要介紹了python中的json數(shù)據(jù)和pyecharts模塊入門,需要的朋友可以參考下2022-12-12
關(guān)于Django使用 django-celery-beat動態(tài)添加定時任務的方法
本文給大家介紹Django使用 django-celery-beat動態(tài)添加定時任務的方法,安裝對應的是celery版本,文中給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-10-10
Python開發(fā)中爬蟲使用代理proxy抓取網(wǎng)頁的方法示例
這篇文章主要介紹了Python開發(fā)中爬蟲使用代理proxy抓取網(wǎng)頁的方法,結(jié)合具體實例形式分析了urllib模塊代理與requests模塊代理兩種實現(xiàn)技巧,需要的朋友可以參考下2017-09-09
python運算符+條件結(jié)構(gòu)+循環(huán)結(jié)構(gòu)
這篇文章主要介紹了python運算符、條件結(jié)構(gòu)、循環(huán)結(jié)構(gòu);算術(shù)運算符、賦值運算符、邏輯運算符等一些相關(guān)內(nèi)容,需要的小伙伴可以參考一下,希望對你的學習有所幫助2022-03-03

