フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

pythonでサイト内の画像をダウンロードと画像圧縮

はじめに

  • サイト内に取得する画像のリストをCSVで事前に用意しておく。
filename
http://www.example.com/images/hoge600444hgea0a9dad15a.png
http://www.example.com/images/hoge600a22222hoge30.png
http://www.example.com/images/hoge6dsa33300a0ae73178e.png

パッケージインストール

pip install Pillow

docs.python.org

コード

import urllib.error
import urllib.request
import glob
from PIL import Image

# 指定したURLの画像を指定したフォルダへ保存する処理
def download_image_file(url, save_path):
    try:
        with urllib.request.urlopen(url) as web_image_file:
            data = web_image_file.read()
            with open(save_path, mode='wb') as local_image_file:
                local_image_file.write(data)
    except urllib.error.URLError as e:
        print(e)

def download(request):
    path = '/<CSVファイルのパスを指定>/images.csv'
    with open(path) as f:
        for url in f:
            url = url.rstrip()  
            file_name = url.split('/')[5] # ファイル名のみ取得。URLの階層次第で数値の指定が異なる
            dst_path = 'data/' + file_name
            download_image_file(url, dst_path)

 # ダウンロードした画像を圧縮してrenameして保存する処理
    files = glob.glob("data/*")
    for file in files:
        image = Image.open(file)
        resize_img = image.resize(image.size, Image.LANCZOS) 
        resize_img.save(file.replace('/', '/resize-'))