Pythonでダウンロードする前にファイルのサイズを取得する

StackOverflow https://stackoverflow.com/questions/5909

  •  08-06-2019
  •  | 
  •  

質問

Web サーバーからディレクトリ全体をダウンロードしています。問題なく動作しますが、ダウンロード前にファイルサイズを取得して、サーバー上で更新されたかどうかを比較する方法がわかりません。これは、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()

@ジョン:素早い回答ありがとうございます。動作しますが、Web サーバー上のファイルサイズは、ダウンロードしたファイルのファイルサイズよりわずかに小さくなります。

例:

Local Size  Server Size
 2.223.533  2.115.516
   664.603    662.121

CR/LF変換と何か関係があるのでしょうか?

役に立ちましたか?

解決

あなたが見ているものを再現しました:

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

これを出力します:

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

ここで私は何を間違っているのでしょうか?os.stat().st_size は正しいサイズを返しませんか?


編集:OK、問題が何であるかはわかりました。

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

これは次のように出力します:

$ 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

両方のファイルをバイナリ読み取り/書き込み用に開いていることを確認してください。

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

他のヒント

returns-urllib-object メソッドの使用 info(), 取得した文書に関するさまざまな情報を取得できます。現在の 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

これは辞書なので、ファイルのサイズを取得するには、次のようにします。 urllibobject.info()['Content-Length']

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

また、ローカル ファイルのサイズを取得するには (比較のために)、os.stat() コマンドを使用できます。

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

ファイルのサイズは Content-Length ヘッダーとして送信されます。urllib を使用して取得する方法は次のとおりです。

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

また、接続しているサーバーがサポートしている場合は、次を参照してください。 Eタグ そしてその 変更された場合-以降 そして 一致しない場合 ヘッダー。

これらを使用すると、Web サーバーのキャッシュ ルールが利用され、 304 未変更 内容が変更されていない場合はステータス コード。

Python3 の場合:

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

Python3 (3.5 でテスト済み) のアプローチの場合、次のことをお勧めします。

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

リクエストGET の代わりに HEAD を使用するベースのソリューション (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))

使用法

$ python filesize-remote-url.py https://httpbin.org/image/jpeg
...
Content-Length                          : 35588
FILE SIZE (MB)                          : 0.03 MB
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top