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

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

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

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


当前回答

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

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

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

其他回答

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模块,其他模块可能会提供更好的东西,但这是我用来解决大多数问题的一个。

如果你安装了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

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

使用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()
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
  output.write(mp3file.read())

open('test.mp3','wb')中的wb以二进制模式打开文件(并擦除任何现有文件),以便您可以使用它保存数据而不仅仅是文本。

基于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/