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

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

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

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


当前回答

为了完整起见,还可以使用子流程包调用任何程序来检索文件。专用于检索文件的程序比Python函数(如urlretrieve)更强大。例如,wget可以递归下载目录(-R),可以处理FTP、重定向、HTTP代理,可以避免重新下载现有文件(-nc),而aria2可以进行多连接下载,这可能会加快下载速度。

import subprocess
subprocess.check_output(['wget', '-O', 'example_output_file.html', 'https://example.com'])

在Jupyter Notebook中,也可以直接使用!语法:

!wget -O example_output_file.html https://example.com

其他回答

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

我同意Corey的观点,urllib2比urllib更完整,如果你想做更复杂的事情,应该使用urllib2模块,但为了让答案更完整,如果你只想要基本的东西,urllib是一个更简单的模块:

import urllib
response = urllib.urlopen('http://www.example.com/sound.mp3')
mp3 = response.read()

会很好。或者,如果你不想处理"response"对象,你可以直接调用read():

import urllib
mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()

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

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

简单但Python 2和Python 3兼容的方式提供了六个库:

from six.moves import urllib
urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
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以二进制模式打开文件(并擦除任何现有文件),以便您可以使用它保存数据而不仅仅是文本。