我有一个小实用程序,用于按计划从网站下载 MP3,然后构建/更新播客 XML 文件,我显然已将其添加到 iTunes 中。

创建/更新 XML 文件的文本处理是用 Python 编写的。我在 Windows 中使用 wget .bat 但要下载实际的 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.requesturllib.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 为拿到它,为实现它。

与其他替代方案相比,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)

这本质上是 @kvance 30 个月前描述的实现。

import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
  output.write(mp3file.read())

wbopen('test.mp3','wb') 以二进制模式打开文件(并删除任何现有文件),以便您可以用它保存数据而不仅仅是文本。

蟒蛇3

  • urllib.request.urlopen

    import urllib.request
    response = urllib.request.urlopen('http://www.example.com/')
    html = response.read()
    
  • urllib.request.urlretrieve

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

蟒蛇2

使用 wget 模块:

import wget
wget.download('url')

Python 2/3 的 PabloG 代码的改进版本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import ( division, absolute_import, print_function, unicode_literals )

import sys, os, tempfile, logging

if sys.version_info >= (3,):
    import urllib.request as urllib2
    import urllib.parse as urlparse
else:
    import urllib2
    import urlparse

def download_file(url, dest=None):
    """ 
    Download and save a file specified by url to dest directory,
    """
    u = urllib2.urlopen(url)

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    filename = os.path.basename(path)
    if not filename:
        filename = 'downloaded.file'
    if dest:
        filename = os.path.join(dest, filename)

    with open(filename, 'wb') as f:
        meta = u.info()
        meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
        meta_length = meta_func("Content-Length")
        file_size = None
        if meta_length:
            file_size = int(meta_length[0])
        print("Downloading: {0} Bytes: {1}".format(url, 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 = "{0:16}".format(file_size_dl)
            if file_size:
                status += "   [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
            status += chr(13)
            print(status, end="")
        print()

    return filename

if __name__ == "__main__":  # Only run if this file is called directly
    print("Testing with 10MB download")
    url = "http://download.thinkbroadband.com/10MB.zip"
    filename = download_file(url)
    print(filename)

写了 获取 纯Python 库就是为了这个目的。它被抽气了 urlretrieve这些功能 从 2.0 版本开始。

简单又简单 Python 2 & Python 3 兼容方式附带 six 图书馆:

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

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

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

会工作得很好。或者,如果您不想处理“响应”对象,您可以调用 读() 直接地:

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

以下是 python 中下载文件最常用的调用:

  1. urllib.urlretrieve ('url_to_file', file_name)

  2. urllib2.urlopen('url_to_file')

  3. requests.get(url)

  4. wget.download('url', file_name)

笔记: urlopenurlretrieve 发现在下载大文件(大小 > 500 MB)时表现相对较差。 requests.get 将文件存储在内存中,直到下载完成。

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 获取进度反馈:

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)

如果安装了wget,则可以使用parallel_sync。

pip 安装并行_同步

from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)

文档:https://pythonhosted.org/parallel_sync/pages/examples.html

这是相当强大的。它可以并行下载文件,失败时重试,甚至可以在远程计算机上下载文件。

在python3中,您可以使用urllib3和shutil libraires。使用 pip 或 pip3 下载它们(取决于 python3 是否默认)

pip3 install urllib3 shutil

然后运行这段代码

import urllib.request
import shutil

url = "http://www.somewebsite.com/something.pdf"
output_file = "save_this_name.pdf"
with urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

请注意,您下载的是 urllib3 但使用 urllib 在代码中

如果速度对您很重要,我对模块做了一个小型性能测试 urllibwget, ,并且关于 wget 我尝试了一次带状态栏,一次不带状态栏。我使用了三个不同的 500MB 文件进行测试(不同的文件 - 以消除在幕后进行某些缓存的可能性)。在 debian 机器上测试,使用 python2。

首先,这些是结果(它们在不同的运行中是相似的):

$ python wget_test.py 
urlretrive_test : starting
urlretrive_test : 6.56
==============
wget_no_bar_test : starting
wget_no_bar_test : 7.20
==============
wget_with_bar_test : starting
100% [......................................................................] 541335552 / 541335552
wget_with_bar_test : 50.49
==============

我执行测试的方式是使用“profile”装饰器。这是完整的代码:

import wget
import urllib
import time
from functools import wraps

def profile(func):
    @wraps(func)
    def inner(*args):
        print func.__name__, ": starting"
        start = time.time()
        ret = func(*args)
        end = time.time()
        print func.__name__, ": {:.2f}".format(end - start)
        return ret
    return inner

url1 = 'http://host.com/500a.iso'
url2 = 'http://host.com/500b.iso'
url3 = 'http://host.com/500c.iso'

def do_nothing(*args):
    pass

@profile
def urlretrive_test(url):
    return urllib.urlretrieve(url)

@profile
def wget_no_bar_test(url):
    return wget.download(url, out='/tmp/', bar=do_nothing)

@profile
def wget_with_bar_test(url):
    return wget.download(url, out='/tmp/')

urlretrive_test(url1)
print '=============='
time.sleep(1)

wget_no_bar_test(url2)
print '=============='
time.sleep(1)

wget_with_bar_test(url3)
print '=============='
time.sleep(1)

urllib 似乎是最快的

只是为了完整起见,还可以使用以下命令调用任何程序来检索文件 subprocess 包裹。专用于检索文件的程序比 Python 函数更强大,例如 urlretrieve. 。例如, wget 可以递归下载目录(-R),可以处理FTP、重定向、HTTP代理,可以避免重新下载现有文件(-nc), 和 aria2 可以进行多连接下载,这可能会加快您的下载速度。

import subprocess
subprocess.check_output(['wget', '-O', 'example_output_file.html', 'https://example.com'])

在Jupyter Notebook中,还可以直接使用 ! 句法:

!wget -O example_output_file.html https://example.com

源代码可以是:

import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()                            
sock.close()                                        
print htmlSource  

我编写了以下代码,它可以在普通 Python 2 或 Python 3 中运行。


import sys
try:
    import urllib.request
    python3 = True
except ImportError:
    import urllib2
    python3 = False


def progress_callback_simple(downloaded,total):
    sys.stdout.write(
        "\r" +
        (len(str(total))-len(str(downloaded)))*" " + str(downloaded) + "/%d"%total +
        " [%3.2f%%]"%(100.0*float(downloaded)/float(total))
    )
    sys.stdout.flush()

def download(srcurl, dstfilepath, progress_callback=None, block_size=8192):
    def _download_helper(response, out_file, file_size):
        if progress_callback!=None: progress_callback(0,file_size)
        if block_size == None:
            buffer = response.read()
            out_file.write(buffer)

            if progress_callback!=None: progress_callback(file_size,file_size)
        else:
            file_size_dl = 0
            while True:
                buffer = response.read(block_size)
                if not buffer: break

                file_size_dl += len(buffer)
                out_file.write(buffer)

                if progress_callback!=None: progress_callback(file_size_dl,file_size)
    with open(dstfilepath,"wb") as out_file:
        if python3:
            with urllib.request.urlopen(srcurl) as response:
                file_size = int(response.getheader("Content-Length"))
                _download_helper(response,out_file,file_size)
        else:
            response = urllib2.urlopen(srcurl)
            meta = response.info()
            file_size = int(meta.getheaders("Content-Length")[0])
            _download_helper(response,out_file,file_size)

import traceback
try:
    download(
        "https://geometrian.com/data/programming/projects/glLib/glLib%20Reloaded%200.5.9/0.5.9.zip",
        "output.zip",
        progress_callback_simple
    )
except:
    traceback.print_exc()
    input()

笔记:

  • 支持“进度条”回调。
  • 从我的网站下载 4 MB 测试 .zip。

您可以使用 pycURL 在 Python 2 和 3 上。

import pycurl

FILE_DEST = 'pycurl.html'
FILE_SRC = 'http://pycurl.io/'

with open(FILE_DEST, 'wb') as f:
    c = pycurl.Curl()
    c.setopt(c.URL, FILE_SRC)
    c.setopt(c.WRITEDATA, f)
    c.perform()
    c.close()

这可能有点晚了,但我看到了 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 中,它应该是“清晰的”。

urlretrieve 和 requests.get 很简单,但事实并非如此。我已经为几个网站获取了数据,包括文本和图像,以上两个可能解决了大部分任务。但对于更通用的解决方案,我建议使用 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 Forbidden 的解决方案。我只尝试了 requests 和 urllib 模块,其他模块可能提供更好的东西,但这是我用来解决大多数问题的模块。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top