我有一个小工具,我用来从一个网站上下载一个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下载文件呢?
当前回答
以下是python中下载文件最常用的调用:
urllib。Urlretrieve ('url_to_file', file_name) urllib2.urlopen(“url_to_file”) requests.get (url) wget。下载(“url”,file_name)
注意:urlopen和urlretrieve在下载大文件(大小为> 500 MB)时表现相对较差。请求。Get将文件存储在内存中,直到下载完成。
其他回答
为了这个目的,用纯Python编写了wget库。从2.0版开始,它就为urlretrieve注入了这些特性。
这可能有点晚了,但我看到了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中,它应该是“清晰的”。
延迟回答,但对于python>=3.6,您可以使用:
import dload
dload.save(url)
安装dload:
pip3 install dload
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模块,其他模块可能会提供更好的东西,但这是我用来解决大多数问题的一个。
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")