Descargar archivos con Python

De WikiEducator
Saltar a: navegación, buscar


Ejemplos con urllib y urllib2

http://www.blog.pythonlibrary.org/2012/06/07/python-101-how-to-download-a-file/

import urllib
import urllib2
 
url = 'http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip'
 
print "downloading with urllib"
urllib.urlretrieve(url, "code.zip")
 
print "downloading with urllib2"
f = urllib2.urlopen(url)
data = f.read()
with open("code2.zip", "wb") as code:
    code.write(data)

http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python

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