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

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

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

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


当前回答

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

其他回答

Python 3

urllib.request.urlopen 进口urllib.request Response = urllib.request.urlopen('http://www.example.com/') HTML = response.read() urllib.request.urlretrieve 进口urllib.request urllib.request.urlretrieve (' http://www.example.com/songs/mp3.mp3 ', ' mp3.mp3 ') 注意:根据文档,urllib.request.urlretrieve是一个“遗留接口”,并且“在未来可能会被弃用”(感谢gerrit)

Python 2

urllib2。urlopen(谢谢科里) 进口urllib2 Response = urllib2.urlopen('http://www.example.com/') HTML = response.read() urllib。urlretrieve(感谢PabloG) 进口urllib urllib.urlretrieve (' http://www.example.com/songs/mp3.mp3 ', ' mp3.mp3 ')

你也可以通过urlretrieve得到进度反馈:

def report(blocknr, blocksize, size):
    current = blocknr*blocksize
    sys.stdout.write("\r{0:.2f}%".format(100.0*current/size))

def downloadFile(url):
    print "\n",url
    fname = url.split('/')[-1]
    print fname
    urllib.urlretrieve(url, fname, report)

延迟回答,但对于python>=3.6,您可以使用:

import dload
dload.save(url)

安装dload:

pip3 install dload

2012年,使用python请求库

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

您可以运行pip install请求来获取它。

请求比替代方法有很多优点,因为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)

这实际上是@kvance在30个月前描述的实现。

以下是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将文件存储在内存中,直到下载完成。