我有一个小工具,我用来从一个网站上下载一个MP3文件,然后构建/更新一个播客XML文件,我已经添加到iTunes。

创建/更新XML文件的文本处理是用Python编写的。但是,我在Windows .bat文件中使用wget来下载实际的MP3文件。我更喜欢用Python编写整个实用程序。

我努力寻找一种用Python实际下载该文件的方法,因此我使用了wget。

那么,如何使用Python下载文件呢?


当前回答

这可能有点晚了,但我看到了pabloG的代码,忍不住添加了一个os.system('cls'),使它看起来很棒!看看吧:

    import urllib2,os

    url = "http://download.thinkbroadband.com/10MB.zip"

    file_name = url.split('/')[-1]
    u = urllib2.urlopen(url)
    f = open(file_name, 'wb')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)
    os.system('cls')
    file_size_dl = 0
    block_sz = 8192
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break

        file_size_dl += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
        status = status + chr(8)*(len(status)+1)
        print status,

    f.close()

如果在Windows以外的环境中运行,你必须使用'cls'以外的东西。在MAC OS X和Linux中,它应该是“清晰的”。

其他回答

Python 3

urllib.request.urlopen 进口urllib.request Response = urllib.request.urlopen('http://www.example.com/') HTML = response.read() urllib.request.urlretrieve 进口urllib.request urllib.request.urlretrieve (' http://www.example.com/songs/mp3.mp3 ', ' mp3.mp3 ') 注意:根据文档,urllib.request.urlretrieve是一个“遗留接口”,并且“在未来可能会被弃用”(感谢gerrit)

Python 2

urllib2。urlopen(谢谢科里) 进口urllib2 Response = urllib2.urlopen('http://www.example.com/') HTML = response.read() urllib。urlretrieve(感谢PabloG) 进口urllib urllib.urlretrieve (' http://www.example.com/songs/mp3.mp3 ', ' mp3.mp3 ')

Python 2/3的PabloG代码的改进版本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import ( division, absolute_import, print_function, unicode_literals )

import sys, os, tempfile, logging

if sys.version_info >= (3,):
    import urllib.request as urllib2
    import urllib.parse as urlparse
else:
    import urllib2
    import urlparse

def download_file(url, dest=None):
    """ 
    Download and save a file specified by url to dest directory,
    """
    u = urllib2.urlopen(url)

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    filename = os.path.basename(path)
    if not filename:
        filename = 'downloaded.file'
    if dest:
        filename = os.path.join(dest, filename)

    with open(filename, 'wb') as f:
        meta = u.info()
        meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
        meta_length = meta_func("Content-Length")
        file_size = None
        if meta_length:
            file_size = int(meta_length[0])
        print("Downloading: {0} Bytes: {1}".format(url, file_size))

        file_size_dl = 0
        block_sz = 8192
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break

            file_size_dl += len(buffer)
            f.write(buffer)

            status = "{0:16}".format(file_size_dl)
            if file_size:
                status += "   [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
            status += chr(13)
            print(status, end="")
        print()

    return filename

if __name__ == "__main__":  # Only run if this file is called directly
    print("Testing with 10MB download")
    url = "http://download.thinkbroadband.com/10MB.zip"
    filename = download_file(url)
    print(filename)

以下是python中下载文件最常用的调用:

urllib。Urlretrieve ('url_to_file', file_name) urllib2.urlopen(“url_to_file”) requests.get (url) wget。下载(“url”,file_name)

注意:urlopen和urlretrieve在下载大文件(大小为> 500 MB)时表现相对较差。请求。Get将文件存储在内存中,直到下载完成。

基于urllib3的新Api实现

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', 'your_url_goes_here')
>>> r.status
   200
>>> r.data
   *****Response Data****

更多信息:https://pypi.org/project/urllib3/

使用5行Python请求

import requests as req

remote_url = 'http://www.example.com/sound.mp3'
local_file_name = 'sound.mp3'

data = req.get(remote_url)

# Save file data to local copy
with open(local_file_name, 'wb')as file:
    file.write(data.content)

现在对远程文件的本地副本执行一些操作