欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)批量下載文件的代碼詳解

 更新時(shí)間:2025年05月06日 10:07:33   作者:猿界新星蔡  
下載文件是我們?cè)谌粘9ぷ髦谐3R龅囊患虑?當(dāng)我們需要從互聯(lián)網(wǎng)上批量下載大量文件時(shí),手動(dòng)一個(gè)一個(gè)去下載顯然不夠高效,為了解決這個(gè)問(wèn)題,我們可以使用Python編寫(xiě)一個(gè)批量下載文件的腳本,讓它自動(dòng)幫我們下載文件,下面小編給大家詳細(xì)介紹一下

概述

該工具是一個(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)示例教程

    python中的json數(shù)據(jù)和pyecharts模塊入門(mén)示例教程

    JSON是一種輕量級(jí)的數(shù)據(jù)交互格式。可以按照.JSON指定的格式去組織和封裝數(shù)據(jù),這篇文章主要介紹了python中的json數(shù)據(jù)和pyecharts模塊入門(mén),需要的朋友可以參考下
    2022-12-12
  • python中Class(類)的超詳細(xì)說(shuō)明

    python中Class(類)的超詳細(xì)說(shuō)明

    這篇文章主要介紹了python中Class(類)的相關(guān)資料,Class類定義了具有相同屬性和方法的對(duì)象集合,對(duì)象是類的實(shí)例,類變量在整個(gè)實(shí)例化的對(duì)象中是公用的,而實(shí)例變量是每個(gè)對(duì)象獨(dú)有的,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-11-11
  • python繪制直方圖的方法

    python繪制直方圖的方法

    這篇文章主要為大家詳細(xì)介紹了python繪制直方圖的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • python虛擬機(jī)解釋器及運(yùn)行過(guò)程

    python虛擬機(jī)解釋器及運(yùn)行過(guò)程

    這篇文章主要為大家介紹了python虛擬機(jī)解釋器及運(yùn)行過(guò)程的介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • 詳解python 模擬豆瓣登錄(豆瓣6.0)

    詳解python 模擬豆瓣登錄(豆瓣6.0)

    這篇文章主要介紹了python模擬豆瓣登錄,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 關(guān)于Django使用 django-celery-beat動(dòng)態(tài)添加定時(shí)任務(wù)的方法

    關(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-10
  • Python開(kāi)發(fā)中爬蟲(chóng)使用代理proxy抓取網(wǎng)頁(yè)的方法示例

    Python開(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-09
  • python運(yùn)算符+條件結(jié)構(gòu)+循環(huán)結(jié)構(gòu)

    python運(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面向?qū)ο笾惖姆庋b操作示例

    Python面向?qū)ο笾惖姆庋b操作示例

    這篇文章主要介紹了Python面向?qū)ο笾惖姆庋b操作,結(jié)合具體實(shí)例形式分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中類方法的定義與使用相關(guān)操作技巧,需要的朋友可以參考下
    2019-06-06
  • 使用Python實(shí)現(xiàn)快速搭建本地HTTP服務(wù)器

    使用Python實(shí)現(xiàn)快速搭建本地HTTP服務(wù)器

    這篇文章主要介紹了如何使用Python快速搭建本地HTTP服務(wù)器,輕松實(shí)現(xiàn)一鍵 HTTP 文件共享,同時(shí)結(jié)合二維碼技術(shù),讓訪問(wèn)更簡(jiǎn)單,感興趣的小伙伴可以了解下
    2025-04-04

最新評(píng)論