如何使用Python通过HTTP下载文件?

我有一个小工具,用于从网站上按计划下载MP3,然后构建/更新我明显添加到iTunes中的播客XML文件。

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

我尽力找到一种方法来实际下载Python中的文件,因此我使用了wget

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


在Python 2中,使用标准库附带的urllib2。

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

这是使用库的最基本的方式,减去任何错误处理。 你也可以做更复杂的事情,比如改变标题。 文档可以在这里找到。


另外,使用urlretrieve

import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

(对于Python 3+使用'import urllib.request'和urllib.request.urlretrieve)

还有一个,有一个“进度条”

import urllib2

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)

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()

2012年,使用python请求库

>>> import requests
>>> 
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760

你可以运行pip install requests来获取它。

与其他选择相比,请求具有许多优点,因为API简单得多。 如果您必须执行身份验证,则尤其如此。 urllib和urllib2在这种情况下非常不直观和痛苦。


2015年12月30日

人们对进度条表示钦佩。 很酷,当然。 现在有几种现成的解决方案,其中包括tqdm

from tqdm import tqdm
import requests

url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)

with open("10MB", "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

这实质上是30个月前描述的实施。

链接地址: http://www.djcxy.com/p/37889.html

上一篇: How do I download a file over HTTP using Python?

下一篇: Issue in bind parameter 'StorageContext'