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

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

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

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


当前回答

你可以在Python 2和3上使用PycURL。

import pycurl

FILE_DEST = 'pycurl.html'
FILE_SRC = 'http://pycurl.io/'

with open(FILE_DEST, 'wb') as f:
    c = pycurl.Curl()
    c.setopt(c.URL, FILE_SRC)
    c.setopt(c.WRITEDATA, f)
    c.perform()
    c.close()

其他回答

如果你安装了wget,你可以使用parallel_sync。

PIP安装parallel_sync

from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)

道格: https://pythonhosted.org/parallel_sync/pages/examples.html

这是非常强大的。它可以并行下载文件,失败时重试,甚至可以在远程机器上下载文件。

你也可以通过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编写了wget库。从2.0版开始,它就为urlretrieve注入了这些特性。

Urlretrieve和请求。得到的都很简单,然而现实却不。 我已经为两个站点提取了数据,包括文本和图像,以上两个可能解决了大部分任务。但如果想要更通用的解决方案,我建议使用urlopen。由于它包含在Python 3标准库中,您的代码可以在任何运行Python 3的机器上运行,而无需预先安装site-package

import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)

#remember to open file in bytes mode
with open(filename, 'wb') as f:
    while True:
        buffer = url_connect.read(buffer_size)
        if not buffer: break

        #an integer value of size of written data
        data_wrote = f.write(buffer)

#you could probably use with-open-as manner
url_connect.close()

当使用Python通过HTTP下载文件时,这个答案提供了HTTP 403禁止的解决方案。我只尝试了请求和urllib模块,其他模块可能会提供更好的东西,但这是我用来解决大多数问题的一个。

另一种方法是调用外部进程,如curl.exe。Curl在默认情况下显示进度条、平均下载速度、剩余时间等,所有这些都整齐地格式化在一个表格中。 将curl.exe放在与脚本相同的目录中

from subprocess import call
url = ""
call(["curl", {url}, '--output', "song.mp3"])

注意:不能使用curl指定输出路径,所以使用os。重命名之后