百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

python编程实践:下载文件模块wget的使用

bigegpt 2024-08-06 12:02 8 浏览

wget是Linux中的一个下载文件的工具,是在Linux下开发的开放源代码的软件,后来被移植到包括Windows在内的各个平台上,也就是wget目前是跨平台的下载软件了。wget工具体积小但功能完善,它支持断点下载功能,同时支持http,https,ftp协议下载方式,支持http代理服务器和设置起来方便简单。

本教程,不是介绍wget软件的如何使用,而是介绍如何在 Python 中使用 wget 模块进行文件下载。通过使用 wget 库,我们可以轻松地从网络上下载各种文件,如文本、图像、视频、音频、压缩、grib2等文件,也就是说所有文件都能下载,当然需要服务器支持,服务器不支持下载的文件,你也下载不了。

网络上有wget模块的讲解,但是大多不系统、不全面。应粉丝的要求,本人通过网络搜索整理、查看源代码、加上自己的理解和实践,形成本教程。

一、安装wget模块

pip install wget

目前wget的版本是3.2。

二、wget模块参数说明

wget.download(url, out=None, bar=bar_adaptive)
  • url:要下载的url。下载url到系统的临时目录中,然后从URL或HTTP headers自动检测文件名并命名,如果当前有相同的名字,则自动改名,添加“(1)(2)”等字符。
  • out:输出文件名或目录
  • bar:跟踪下载进度的函数(可视化等)
  • return:返回url被下载到的文件名

三、下载文件

下载文件实例1:

url:是我随便在网上找的一个链接。它是一个压缩软件执行程序。

import wget
url = 'https://motzdown.mydown.com/package/wincompress_1/win%E8%A7%A3%E5%8E%8B%E7%BC%A9_1800_1_31_2528.exe'
localfile = wget.download(url)
print(localfile)  #win%E8%A7%A3%E5%8E%8B%E7%BC%A9_1800_1_31_2528 1.exe

返回的是:win%E8%A7%A3%E5%8E%8B%E7%BC%A9_1800_1_31_2528 1.exe,也就是下载的文件名。
下载文件实例2:

下载文件并保存在当前目录下。

import wget
url = 'https://motzdown.mydown.com/package/wincompress_1/win%E8%A7%A3%E5%8E%8B%E7%BC%A9_1800_1_31_2528.exe'
localfile = './win解压缩_1800_1_31_2528.exe'
wget.download(url,out=localfile)

运行的效果下图所示。

它有一个默认的下载进度栏,非常直观和方便。

三、设置代理

有时,我们下载文件的过程中,需要用到http代理服务器来下载文件,这时怎么办,wget 模块也提供了相应的功能。这时我们可以使用 proxy参数来指定http代理服务器的地址。示例如下:

import wget
url = 'https://xxx.xxx.com/test.rar'
localfile = './test.rar'
proxy = 'http://proxy.xxx.xxx.com:20080'
wget.download(url, localfile, proxy=proxy)

四、下载进度

翻看wget的源程序,bar_adaptive函数就是它下载文件的进度显示的函数。它有三个参数,current:当前已经下载文件的大小, total:文件的大小, width=80:显示字符的宽度。

这个例子我就不具体讲解了,有兴趣的可以仔细学习一下。

def bar_adaptive(current, total, width=80):
    """Return progress bar string for given values in one of three
    styles depending on available width:

        [..  ] downloaded / total
        downloaded / total
        [.. ]

    if total value is unknown or <= 0, show bytes counter using two
    adaptive styles:

        %s / unknown
        %s

    if there is not enough space on the screen, do not display anything

    returned string doesn't include control characters like \r used to
    place cursor at the beginning of the line to erase previous content.

    this function leaves one free character at the end of string to
    avoid automatic linefeed on Windows.
    """

    # process special case when total size is unknown and return immediately
    if not total or total < 0:
        msg = "%s / unknown" % current
        if len(msg) < width:    # leaves one character to avoid linefeed
            return msg
        if len("%s" % current) < width:
            return "%s" % current

    # --- adaptive layout algorithm ---
    #
    # [x] describe the format of the progress bar
    # [x] describe min width for each data field
    # [x] set priorities for each element
    # [x] select elements to be shown
    #   [x] choose top priority element min_width < avail_width
    #   [x] lessen avail_width by value if min_width
    #   [x] exclude element from priority list and repeat
    
    #  10% [.. ]  10/100
    # pppp bbbbb sssssss

    min_width = {
      'percent': 4,  # 100%
      'bar': 3,      # [.]
      'size': len("%s" % total)*2 + 3, # 'xxxx / yyyy'
    }
    priority = ['percent', 'bar', 'size']

    # select elements to show
    selected = []
    avail = width
    for field in priority:
      if min_width[field] < avail:
        selected.append(field)
        avail -= min_width[field]+1   # +1 is for separator or for reserved space at
                                      # the end of line to avoid linefeed on Windows
    # render
    output = ''
    for field in selected:

      if field == 'percent':
        # fixed size width for percentage
        output += ('%s%%' % (100 * current // total)).rjust(min_width['percent'])
      elif field == 'bar':  # [. ]
        # bar takes its min width + all available space
        output += bar_thermometer(current, total, min_width['bar']+avail)
      elif field == 'size':
        # size field has a constant width (min == max)
        output += ("%s / %s" % (current, total)).rjust(min_width['size'])

      selected = selected[1:]
      if selected:
        output += ' '  # add field separator

    return output

下面我给出了三个小例子,希望给大家以启迪。

例子1,显示直接用sys.stdout.write,而且用了"\r"符号,只回车不换行。也就是从头开始显示,但不换新行。

import sys
import wget

url = 'https://motzdown.mydown.com/package/wincompress_1/win%E8%A7%A3%E5%8E%8B%E7%BC%A9_1800_1_31_2528.exe'
localfile = './win解压缩_1800_1_31_2528.exe'

def bar_progress(current, total, width=80):
     progress_message = "Downloading: %d%% [%d / %d] bytes" % (current / total * 100, current, total)
     # 不要使用print(),因为它显示,总是会另起新的一行显示。
     sys.stdout.write("\r" + progress_message)
     sys.stdout.flush()

wget.download(url,out=localfile,bar=bar_progress)

运行效果如下:

例子2,和例子1类似,但是实现了下载的进度条。

import sys
import wget

url = 'https://motzdown.mydown.com/package/wincompress_1/win%E8%A7%A3%E5%8E%8B%E7%BC%A9_1800_1_31_2528.exe'
localfile = './win解压缩_1800_1_31_2528.exe'

def progress_bar(current, total, width=80):
    progress = current / total
    bar = '#' * int(progress * width)
    percentage = round(progress * 100, 2)
    tempstr = f'[{bar:<{width}}] {percentage}%'
    sys.stdout.write("\r" + tempstr)
    sys.stdout.flush()

wget.download(url,out=localfile,bar=progress_bar)

运行效果如下:

例子3,是在和例子2基础上改写,进度条从“######”改为“..........”,没有使用sys.stdout.write,而是直接返回要显示的字符串。

这就是直接仿照官方源代码改写的。也就是说,自定义的进度条,只需要返回要显示的字符串即可。

import sys
import wget

url = 'https://motzdown.mydown.com/package/wincompress_1/win%E8%A7%A3%E5%8E%8B%E7%BC%A9_1800_1_31_2528.exe'
localfile = './win解压缩_1800_1_31_2528.exe'

def progress_bar(current, total, width=80):
    progress = current / total
    bar = '.' * int(progress * width)
    percentage = round(progress * 100, 2)
    tempstr = f'[{bar:<{width}}] {percentage}%'
    return tempstr 

wget.download(url,out=localfile,bar=progress_bar)

运行效果如下:

需要说明的是,有时您下载的文件大小,服务器没有给出,这时total的数值就不知道。对于这一点,bar_adaptive的代码考虑得非常全面。本教程给的三个自定义进度函数,没有考虑这种情况,如果遇见这种情况,程序会出错退出的。有兴趣的粉丝,可以参照bar_adaptive的代码进行完善。有不懂的,可以在评论区讨论。

五、异常处理

在使用 wget 进行文件下载时,不可避免地会遇到一些异常的情况,如连接到服务器出现问题、下载过程中出现中断或出现错误等。为了确保程序的不意外中断、能继续执行后面的任务,我们可以使用异常处理来处理这些异常情况,这样我们可以根据日志来判断程序执行的情况,从而采取具体的处理措施。当然这种异常处理是一般程序的处理方法,这里只是介绍,非wget所独有。示例如下:

try:
    wget.download(url,  localfile)
except Exception as e:
    print(f'An error occurred: {e}')

相关推荐

Go语言泛型-泛型约束与实践(go1.7泛型)

来源:械说在Go语言中,Go泛型-泛型约束与实践部分主要探讨如何定义和使用泛型约束(Constraints),以及如何在实际开发中利用泛型进行更灵活的编程。以下是详细内容:一、什么是泛型约束?**泛型...

golang总结(golang实战教程)

基础部分Go语言有哪些优势?1简单易学:语法简洁,减少了代码的冗余。高效并发:内置强大的goroutine和channel,使并发编程更加高效且易于管理。内存管理:拥有自动垃圾回收机制,减少内...

Go 官宣:新版 Protobuf API(go pro版本)

原文作者:JoeTsai,DamienNeil和HerbieOng原文链接:https://blog.golang.org/a-new-go-api-for-protocol-buffer...

Golang开发的一些注意事项(一)(golang入门项目)

1.channel关闭后读的问题当channel关闭之后再去读取它,虽然不会引发panic,但会直接得到零值,而且ok的值为false。packagemainimport"...

golang 托盘菜单应用及打开系统默认浏览器

之前看到一个应用,用go语言编写,说是某某程序的windows图形化客户端,体验一下发现只是一个托盘,然后托盘菜单的控制面板功能直接打开本地浏览器访问程序启动的webserver网页完成gui相关功...

golang标准库每日一库之 io/ioutil

一、核心函数概览函数作用描述替代方案(Go1.16+)ioutil.ReadFile(filename)一次性读取整个文件内容(返回[]byte)os.ReadFileioutil.WriteFi...

文件类型更改器——GoLang 中的 CLI 工具

我是如何为一项琐碎的工作任务创建一个简单的工具的,你也可以上周我开始玩GoLang,它是一种由Google制作的类C编译语言,非常轻量和快速,事实上它经常在Techempower的基准测...

Go (Golang) 中的 Channels 简介(golang channel长度和容量)

这篇文章重点介绍Channels(通道)在Go中的工作方式,以及如何在代码中使用它们。在Go中,Channels是一种编程结构,它允许我们在代码的不同部分之间移动数据,通常来自不同的goro...

Golang引入泛型:Go将Interface「」替换为“Any”

现在Go将拥有泛型:Go将Interface{}替换为“Any”,这是一个类型别名:typeany=interface{}这会引入了泛型作好准备,实际上,带有泛型的Go1.18Beta...

一文带你看懂Golang最新特性(golang2.0特性)

作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...

Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移

以下文章来源于GoOfficialBlog,作者GoOfficialBlogIntroductionagollo是Apollo的Golang客户端Apollo(阿波罗)是携程框架部门研...

Golang使用grpc详解(golang gcc)

gRPC是Google开源的一种高性能、跨语言的远程过程调用(RPC)框架,它使用ProtocolBuffers作为序列化工具,支持多种编程语言,如C++,Java,Python,Go等。gR...

Etcd服务注册与发现封装实现--golang

服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...

Golang:将日志以Json格式输出到Kafka

在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...

如何从 PHP 过渡到 Golang?(php转golang)

我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...