Transmita archivos binarios grandes con urllib2 a archivo


Utilizo el siguiente código para transmitir archivos grandes desde Internet a un archivo local:

fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
    fp.write(line)
fp.close()

Esto funciona pero se descarga muy lentamente. ¿Hay una manera más rápida? (Los archivos son grandes, así que no quiero mantenerlos en memoria.)

Author: Peter Mortensen, 2009-10-05

4 answers

No hay razón para trabajar línea por línea (trozos pequeños Y requiere Python para encontrar los extremos de la línea para usted!- ), simplemente divídelo en trozos más grandes, por ejemplo:

# from urllib2 import urlopen # Python 2
from urllib.request import urlopen # Python 3

response = urlopen(url)
CHUNK = 16 * 1024
with open(file, 'wb') as f:
    while True:
        chunk = response.read(CHUNK)
        if not chunk:
            break
        f.write(chunk)

Experimente un poco con varios tamaños de TROZOS para encontrar el "punto óptimo" para sus necesidades.

 100
Author: Alex Martelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 20:12:43

También puedes usar shutil :

import shutil
try:
    from urllib.request import urlopen # Python 3
except ImportError:
    from urllib2 import urlopen # Python 2

def get_large_file(url, file, length=16*1024):
    req = urlopen(url)
    with open(file, 'wb') as fp:
        shutil.copyfileobj(req, fp, length)
 61
Author: Tiago,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 20:07:06

Solía usar el módulo mechanize y su Navegador.método retrieve (). En el pasado, tomó 100% CPU y descargó las cosas muy lentamente, pero algunas versiones recientes corrigieron este error y funciona muy rápidamente.

Ejemplo:

import mechanize
browser = mechanize.Browser()
browser.retrieve('http://www.kernel.org/pub/linux/kernel/v2.6/testing/linux-2.6.32-rc1.tar.bz2', 'Downloads/my-new-kernel.tar.bz2')

Mechanize se basa en urllib2, por lo que urllib2 también puede tener un método similar... pero no puedo encontrar ninguna ahora.

 6
Author: liori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-04 23:07:49

Puede usar urllib.recuperar() para descargar archivos:

Ejemplo:

try:
    from urllib import urlretrieve # Python 2

except ImportError:
    from urllib.request import urlretrieve # Python 3

url = "http://www.examplesite.com/myfile"
urlretrieve(url,"./local_file")
 4
Author: Aravindh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-07 19:14:25