今回はPythonのrequestsというライブラリを使って、インターネットから画像を自動ダウンロードする処理についてです。
目次
ライブラリのインストール
今回はrequestsのみなのでこれだけです。
pip install requests
画像ダウンロード実装
実装は以下の通りです。特に解説するほどでもないと思いますが。
save_imageは画像の保存処理です。データとファイルパスを引数で受け取って保存します。
download_imageはrequestsを使ってデータを取得する処理です。
URLを引数で受け取って、そのURLを使ってリクエストを投げます。タイムアウトはテキトーにしてます。
リクエストしたレスポンスのステータスコード、画像かどうかのチェックをします。
def save_image(filename, image):
# ファイルをローカルに保存
with open(filename, "wb") as file:
file.write(image)
def download_image(url):
# リクエストを投げる
response = requests.get(url, timeout=100)
# ステータスコードがエラー
if response.status_code != 200:
raise RuntimeError("取得失敗")
content_type = response.headers["content-type"]
# 画像ではない
if 'image' not in content_type:
raise RuntimeError("画像ではありません")
return response.content
image = download_image(<URL>)
save_image(<ファイル名>, image)
連番画像を複数ダウンロード
上の二つのメソッドがあれば、画像URLが連番(1.jpg, 2.jpg…)ならfor文回して一気に何枚もダウンロードできます。そのサンプルも書いておきます。
サーバの負荷を考慮して1枚ダウンロードしたら1.5秒待つようにしています。
def download_images(root_url: str, local_dirpath: str, starts_with=1, end_with=1000):
print("=======================downloading images=======================")
# 保存するディレクトリ作成
root_dirpath = "自分の好きなフォルダ名"
try:
os.mkdir(root_dirpath)
print("making directory is successful!!!")
# すでにフォルダがある場合は無視
except FileExistsError:
pass
# ダウンロード先のURLを生成してダウンロード回す
for i in range(starts_with, end_with+1):
# ファイル名、URLを生成しダウンロード・保存
filename = f"{str(i)}.jpg"
url = f"{root_url}/{filename}"
save_image(f"{root_dirpath}/{filename}", download_image(url))
# サーバの負荷を考慮して1.5秒待つ
time.sleep(1.5)
print("finish downloading image: {}".format(filename))
print("=======================finish downloading images=======================")