LoginSignup
1
2

More than 5 years have passed since last update.

拡張子を判断して画像ダウンロード

Last updated at Posted at 2017-01-22

昔々書いていたブログにはエクスポート機能がありませんでした。
画像のURL一覧はcurlやgrepで作ったんですがURLが/Img?hogehogeみたいな形式なのでwget -i で保存してもImg0.1とかImg0.2とかになっちゃいました。

よくよく探せばcurlやらwgetでうまいことやるオプションがあるのかもしれませんが探すのも面倒なのでスクリプトを書いてみました。

ファイル名はLast-Modifiedから更新年月日、context-typeから拡張子を取っています。
同じ更新年月日のファイルがあったので通し番号もつけてます。

使い方

cat url_list.txt | python get-contents.py

スクリプト

get-contents.py
# -*- coding: utf-8 -*-

import sys
import requests
import datetime
import struct

cnt = 0
for line in sys.stdin.readlines():
    r = requests.get(line.strip())
    # print(r.headers)
    ext = (r.headers['Content-Type'].split('/'))[1]
    lm = datetime.datetime.strptime(
        r.headers['Last-Modified'], '%a, %d %b %Y %H:%M:%S GMT')
    fname = lm.strftime('%Y%m%d-%H%M%S') + ('-%03d.' % cnt) + ext
    print(fname)
    with open(fname, "wb") as fout:
        for x in r.content:
            fout.write(struct.pack("B", x))
    cnt = cnt + 1

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2