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

我有一个小的实用程序,能够用来按计划从网站上下载MP3,而后构建/更新我显然已添加到iTunes的播客XML文件。 html

建立/更新XML文件的文本处理是用Python编写的。 我在Windows .bat文件中使用wget下载实际的MP3。 我更但愿将整个实用程序用Python编写。 python

我一直在努力寻找一种方法来实际下载Python中的文件,所以为何要诉诸wget网站

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


#1楼

在2012年,使用python请求库 url

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

您能够运行pip install requests来获取它。 spa

与API相比,请求具备许多优点,由于API更加简单。 若是必须执行身份验证,则尤为如此。 在这种状况下,urllib和urllib2很是不直观且使人痛苦。 code


2015-12-30 orm

人们对进度条表示钦佩。 确定很酷。 如今有几种现成的解决方案,包括tqdmhtm

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)

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


#2楼

用于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)

#3楼

为此,在纯Python中编写了wget库。 从2.0版开始, urlretrieve具备这些功能


#4楼

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


#5楼

源代码能够是:

import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()                            
sock.close()                                        
print htmlSource
相关文章
相关标签/搜索