我有一个小工具,我用来从一个网站上下载一个MP3文件,然后构建/更新一个播客XML文件,我已经添加到iTunes。
创建/更新XML文件的文本处理是用Python编写的。但是,我在Windows .bat文件中使用wget来下载实际的MP3文件。我更喜欢用Python编写整个实用程序。
我努力寻找一种用Python实际下载该文件的方法,因此我使用了wget。
那么,如何使用Python下载文件呢?
我有一个小工具,我用来从一个网站上下载一个MP3文件,然后构建/更新一个播客XML文件,我已经添加到iTunes。
创建/更新XML文件的文本处理是用Python编写的。但是,我在Windows .bat文件中使用wget来下载实际的MP3文件。我更喜欢用Python编写整个实用程序。
我努力寻找一种用Python实际下载该文件的方法,因此我使用了wget。
那么,如何使用Python下载文件呢?
当前回答
我同意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()
其他回答
你可以使用python请求
import os
import requests
outfile = os.path.join(SAVE_DIR, file_name)
response = requests.get(URL, stream=True)
with open(outfile,'wb') as output:
output.write(response.content)
你可以使用shutil
import os
import requests
import shutil
outfile = os.path.join(SAVE_DIR, file_name)
response = requests.get(url, stream = True)
with open(outfile, 'wb') as f:
shutil.copyfileobj(response.content, f)
如果你从受限的url下载,不要忘记在标题中包含访问令牌
import os,requests
def download(url):
get_response = requests.get(url,stream=True)
file_name = url.split("/")[-1]
with open(file_name, 'wb') as f:
for chunk in get_response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
download("https://example.com/example.jpg")
还有一个,使用urlretrieve:
import urllib.request
urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
(对于Python 2使用import urllib和urllib.urlretrieve)
我同意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()
这可能有点晚了,但我看到了pabloG的代码,忍不住添加了一个os.system('cls'),使它看起来很棒!看看吧:
import urllib2,os
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)
os.system('cls')
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()
如果在Windows以外的环境中运行,你必须使用'cls'以外的东西。在MAC OS X和Linux中,它应该是“清晰的”。