DEV

Python3 - ファイルのダウンロード

urllib.request.urlretrieveを使うとできます。本家の説明ページはここです。なんか廃止されるかもしれないとか書いてあるけど。他にはRequestsパッケージを使う方法もあります。

urllib.request.urlretrieveを使う

圧縮ファイルをダウンロードして展開する

import urllib.request
import os
import tarfile
dirpath = './hoge'
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
filename = url.split('/')[-1]
filepath = os.path.join(dirpath, filename)
urllib.request.urlretrieve(url, filepath)
tarfile.open(filepath, 'r:gz').extractall(dirpath)

ダウンロード中に進捗を表示する

import os
import sys
import urllib.request
import tarfile
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
dirpath = './hoge'
filename = url.split('/')[-1]
filepath = os.path.join(dirpath, filename)
def _progress(cnt, chunk, total):
now = cnt * chunk
if(now > total): now = total
sys.stdout.write('\rdownloading {} {} / {} ({:.1%})'.format(filename, now, total, now/total))
sys.stdout.flush()
urllib.request.urlretrieve(url, filepath, _progress)
tarfile.open(filepath, 'r:gz').extractall(dirpath)

Requestsパッケージを使う

画像ファイルをダウンロードして表示する

コードサンプル

import requests
from PIL import Image
from io import BytesIO
url = 'http://docs.python.jp/3/_static/py.png'
r = requests.get(url)
Image.open(BytesIO(r.content)).show()

圧縮ファイルをダウンロードして展開する

dirpath = './hoge'
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
filename = url.split('/')[-1]
filepath = os.path.join(dirpath, filename)
r = requests.get(url)
with open(filepath, 'wb') as f:
f.write(r.content)
tarfile.open(filepath, 'r:gz').extractall(dirpath)

ダウンロード中に進捗を表示する

import os
import sys
import requests
import tarfile
dirpath = './hoge'
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
filename = url.split('/')[-1]
filepath = os.path.join(dirpath, filename)
r = requests.get(url, stream=True)
total = int(r.headers.get('content-length'))
now = 0
with open(filepath, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
now += 1024
if(now > total): now = total;
sys.stdout.write('\rdownloading {} {} / {} ({:.1%})'.format(filename, now, total, now/total))
sys.stdout.flush()
tarfile.open(filepath, 'r:gz').extractall(dirpath)