Domanda

Sto scaricando un'intera directory da un server web.Funziona bene, ma non riesco a capire come ottenere la dimensione del file prima del download per confrontare se è stato aggiornato sul server o meno.È possibile farlo come se stessi scaricando il file da un server FTP?

import urllib
import re

url = "http://www.someurl.com"

# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()

f = open ("temp.htm", "w")
f.write (html)
f.close()

# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)

for fname in fnames:
    print fname, "..."

    f = urllib.urlopen(url + "/" + fname)

    #### Here I want to check the filesize to download or not #### 
    file = f.read()
    f.close()

    f = open (fname, "w")
    f.write (file)
    f.close()

@Jon:grazie per la tua rapida rispostaFunziona, ma la dimensione del file sul server web è leggermente inferiore alla dimensione del file scaricato.

Esempi:

Local Size  Server Size
 2.223.533  2.115.516
   664.603    662.121

Ha qualcosa a che fare con la conversione CR/LF?

È stato utile?

Soluzione

Ho riprodotto quello che stai vedendo:

import urllib, os
link = "http://python.org"
print "opening url:", link
site = urllib.urlopen(link)
meta = site.info()
print "Content-Length:", meta.getheaders("Content-Length")[0]

f = open("out.txt", "r")
print "File on disk:",len(f.read())
f.close()


f = open("out.txt", "w")
f.write(site.read())
site.close()
f.close()

f = open("out.txt", "r")
print "File on disk after download:",len(f.read())
f.close()

print "os.stat().st_size returns:", os.stat("out.txt").st_size

Emette questo:

opening url: http://python.org
Content-Length: 16535
File on disk: 16535
File on disk after download: 16535
os.stat().st_size returns: 16861

Cosa sto facendo di sbagliato qui?os.stat().st_size non restituisce la dimensione corretta?


Modificare:Ok, ho capito quale era il problema:

import urllib, os
link = "http://python.org"
print "opening url:", link
site = urllib.urlopen(link)
meta = site.info()
print "Content-Length:", meta.getheaders("Content-Length")[0]

f = open("out.txt", "rb")
print "File on disk:",len(f.read())
f.close()


f = open("out.txt", "wb")
f.write(site.read())
site.close()
f.close()

f = open("out.txt", "rb")
print "File on disk after download:",len(f.read())
f.close()

print "os.stat().st_size returns:", os.stat("out.txt").st_size

questo restituisce:

$ python test.py
opening url: http://python.org
Content-Length: 16535
File on disk: 16535
File on disk after download: 16535
os.stat().st_size returns: 16535

Assicurati di aprire entrambi i file per la lettura/scrittura binaria.

// open for binary write
open(filename, "wb")
// open for binary read
open(filename, "rb")

Altri suggerimenti

Utilizzando il metodo dell'oggetto restituito-urllib info(), è possibile ottenere varie informazioni sul documento recuperato.Esempio di acquisizione dell'attuale logo di Google:

>>> import urllib
>>> d = urllib.urlopen("http://www.google.co.uk/logos/olympics08_opening.gif")
>>> print d.info()

Content-Type: image/gif
Last-Modified: Thu, 07 Aug 2008 16:20:19 GMT  
Expires: Sun, 17 Jan 2038 19:14:07 GMT 
Cache-Control: public 
Date: Fri, 08 Aug 2008 13:40:41 GMT 
Server: gws 
Content-Length: 20172 
Connection: Close

È un decreto, quindi per ottenere la dimensione del file, lo fai urllibobject.info()['Content-Length']

print f.info()['Content-Length']

E per ottenere la dimensione del file locale (per confronto), puoi usare il comando os.stat():

os.stat("/the/local/file.zip").st_size

La dimensione del file viene inviata come intestazione Content-Length.Ecco come ottenerlo con urllib:

>>> site = urllib.urlopen("http://python.org")
>>> meta = site.info()
>>> print meta.getheaders("Content-Length")
['16535']
>>>

Inoltre, se il server a cui ti stai connettendo lo supporta, guarda Etag e il Se-modificato-dal E Se non corrisponde intestazioni.

L'utilizzo di questi trarrà vantaggio dalle regole di memorizzazione nella cache del server Web e restituirà a 304 Non modificato codice di stato se il contenuto non è cambiato.

In Python3:

>>> import urllib.request
>>> site = urllib.request.urlopen("http://python.org")
>>> print("FileSize: ", site.length)

Per un approccio Python3 (testato su 3.5) consiglierei:

with urlopen(file_url) as in_file, open(local_file_address, 'wb') as out_file:
    print(in_file.getheader('Content-Length'))
    out_file.write(response.read())

UN richiestesoluzione basata su HEAD invece di GET (stampa anche le intestazioni HTTP):

#!/usr/bin/python
# display size of a remote file without downloading

from __future__ import print_function
import sys
import requests

# number of bytes in a megabyte
MBFACTOR = float(1 << 20)

response = requests.head(sys.argv[1], allow_redirects=True)

print("\n".join([('{:<40}: {}'.format(k, v)) for k, v in response.headers.items()]))
size = response.headers.get('content-length', 0)
print('{:<40}: {:.2f} MB'.format('FILE SIZE', int(size) / MBFACTOR))

Utilizzo

$ python filesize-remote-url.py https://httpbin.org/image/jpeg
...
Content-Length                          : 35588
FILE SIZE (MB)                          : 0.03 MB
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top