Python實(shí)現(xiàn)批量下載文件的代碼詳解
概述
該工具是一個(gè)用 Python 編寫(xiě)的批量下載文件腳本。它從配置文件中讀取下載任務(wù)列表,并并行下載文件,同時(shí)顯示下載進(jìn)度。該工具使用 requests 庫(kù)進(jìn)行 HTTP 請(qǐng)求,使用 tqdm 庫(kù)顯示下載進(jìn)度,并使用 configparser 庫(kù)讀取配置文件。
依賴
在使用該工具之前,請(qǐng)確保已安裝以下庫(kù):
requests
tqdm
可以使用以下命令安裝所需的庫(kù):
pip install requests tqdm
配置文件
創(chuàng)建一個(gè)配置文件(例如 downloads.ini
),其中包含下載任務(wù)列表。配置文件使用 INI 格式,每個(gè)下載任務(wù)有一個(gè)單獨(dú)的節(jié),每個(gè)節(jié)包含 url
和 path
兩個(gè)字段。
示例配置文件 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): """ 下載單個(gè)文件并保存到指定路徑,并顯示下載進(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
代碼功能說(shuō)明
- 導(dǎo)入庫(kù)
import os import requests from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import configparser import argparse
download_file
函數(shù):下載單個(gè)文件并保存到指定路徑,同時(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)
- 請(qǐng)確保配置文件中的 URL 是有效的下載鏈接。
- 如果下載過(guò)程中出現(xiàn)錯(cuò)誤,腳本會(huì)輸出相應(yīng)的錯(cuò)誤信息。
到此這篇關(guān)于Python實(shí)現(xiàn)批量下載文件的代碼詳解的文章就介紹到這了,更多相關(guān)Python批量下載文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中的json數(shù)據(jù)和pyecharts模塊入門(mén)示例教程
JSON是一種輕量級(jí)的數(shù)據(jù)交互格式。可以按照.JSON指定的格式去組織和封裝數(shù)據(jù),這篇文章主要介紹了python中的json數(shù)據(jù)和pyecharts模塊入門(mén),需要的朋友可以參考下2022-12-12python中Class(類)的超詳細(xì)說(shuō)明
這篇文章主要介紹了python中Class(類)的相關(guān)資料,Class類定義了具有相同屬性和方法的對(duì)象集合,對(duì)象是類的實(shí)例,類變量在整個(gè)實(shí)例化的對(duì)象中是公用的,而實(shí)例變量是每個(gè)對(duì)象獨(dú)有的,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-11-11python虛擬機(jī)解釋器及運(yùn)行過(guò)程
這篇文章主要為大家介紹了python虛擬機(jī)解釋器及運(yùn)行過(guò)程的介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06關(guān)于Django使用 django-celery-beat動(dòng)態(tài)添加定時(shí)任務(wù)的方法
本文給大家介紹Django使用 django-celery-beat動(dòng)態(tài)添加定時(shí)任務(wù)的方法,安裝對(duì)應(yīng)的是celery版本,文中給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-10-10Python開(kāi)發(fā)中爬蟲(chóng)使用代理proxy抓取網(wǎng)頁(yè)的方法示例
這篇文章主要介紹了Python開(kāi)發(fā)中爬蟲(chóng)使用代理proxy抓取網(wǎng)頁(yè)的方法,結(jié)合具體實(shí)例形式分析了urllib模塊代理與requests模塊代理兩種實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-09-09python運(yùn)算符+條件結(jié)構(gòu)+循環(huán)結(jié)構(gòu)
這篇文章主要介紹了python運(yùn)算符、條件結(jié)構(gòu)、循環(huán)結(jié)構(gòu);算術(shù)運(yùn)算符、賦值運(yùn)算符、邏輯運(yùn)算符等一些相關(guān)內(nèi)容,需要的小伙伴可以參考一下,希望對(duì)你的學(xué)習(xí)有所幫助2022-03-03使用Python實(shí)現(xiàn)快速搭建本地HTTP服務(wù)器
這篇文章主要介紹了如何使用Python快速搭建本地HTTP服務(wù)器,輕松實(shí)現(xiàn)一鍵 HTTP 文件共享,同時(shí)結(jié)合二維碼技術(shù),讓訪問(wèn)更簡(jiǎn)單,感興趣的小伙伴可以了解下2025-04-04