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

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

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

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


当前回答

另一种可能是使用内置的http.client:

from http import HTTPStatus, client
from shutil import copyfileobj

# using https
connection = client.HTTPSConnection("www.example.com")
with connection.request("GET", "/noise.mp3") as response:
    if response.status == HTTPStatus.OK:
        copyfileobj(response, open("noise.mp3")
    else:
        raise Exception("request needs work")

HTTPConnection对象被认为是“低级的”,因为它只执行一次所需的请求,并假设开发人员将对它或脚本进行子类化,以处理HTTP的细微差别。诸如请求之类的库倾向于处理更特殊的情况,例如自动跟随重定向等等。

其他回答

我写了下面的代码,它可以在普通的Python 2或Python 3中工作。


import sys
try:
    import urllib.request
    python3 = True
except ImportError:
    import urllib2
    python3 = False


def progress_callback_simple(downloaded,total):
    sys.stdout.write(
        "\r" +
        (len(str(total))-len(str(downloaded)))*" " + str(downloaded) + "/%d"%total +
        " [%3.2f%%]"%(100.0*float(downloaded)/float(total))
    )
    sys.stdout.flush()

def download(srcurl, dstfilepath, progress_callback=None, block_size=8192):
    def _download_helper(response, out_file, file_size):
        if progress_callback!=None: progress_callback(0,file_size)
        if block_size == None:
            buffer = response.read()
            out_file.write(buffer)

            if progress_callback!=None: progress_callback(file_size,file_size)
        else:
            file_size_dl = 0
            while True:
                buffer = response.read(block_size)
                if not buffer: break

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

                if progress_callback!=None: progress_callback(file_size_dl,file_size)
    with open(dstfilepath,"wb") as out_file:
        if python3:
            with urllib.request.urlopen(srcurl) as response:
                file_size = int(response.getheader("Content-Length"))
                _download_helper(response,out_file,file_size)
        else:
            response = urllib2.urlopen(srcurl)
            meta = response.info()
            file_size = int(meta.getheaders("Content-Length")[0])
            _download_helper(response,out_file,file_size)

import traceback
try:
    download(
        "https://geometrian.com/data/programming/projects/glLib/glLib%20Reloaded%200.5.9/0.5.9.zip",
        "output.zip",
        progress_callback_simple
    )
except:
    traceback.print_exc()
    input()

注:

支持“进度条”回调。 从我的网站上下载一个4 MB的测试包。zip。

源代码可以是:

import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()                            
sock.close()                                        
print htmlSource  

使用urllib.request.urlopen ():

import urllib.request
with urllib.request.urlopen('http://www.example.com/') as f:
    html = f.read().decode('utf-8')

这是使用库的最基本的方法,没有任何错误处理。您还可以执行更复杂的操作,例如更改头文件。

在Python 2中,该方法在urllib2中:

import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()

你也可以通过urlretrieve得到进度反馈:

def report(blocknr, blocksize, size):
    current = blocknr*blocksize
    sys.stdout.write("\r{0:.2f}%".format(100.0*current/size))

def downloadFile(url):
    print "\n",url
    fname = url.split('/')[-1]
    print fname
    urllib.urlretrieve(url, fname, report)

以下是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将文件存储在内存中,直到下载完成。