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

时间:2020-03-05 18:42:05  来源:igfitidea点击:

我有一个小的实用程序,可以用来按计划从网站上下载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()

减去任何错误处理,这是使用该库的最基本方法。我们还可以执行更复杂的操作,例如更改标题。该文档可以在这里找到。

回答

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`以二进制模式打开文件(并擦除任何现有文件),因此我们可以用它保存数据,而不仅仅是文本。

回答

我同意Corey的观点,urllib2比urllib更完整,如果我们想做更复杂的事情,应该使用urllib2,但是为了使答案更完整,如果我们只需要基础知识,则urllib是一个更简单的模块:

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

会很好的工作。或者,如果我们不想处理"响应"对象,则可以直接调用read():

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

回答

再使用urlretrieve

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

(对于Python 3+,请使用"导入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()