やっつけスクリプト(3)
とりあえず晒します。
要件:
- 元コンテンツのHTMLファイルはテンプレート言語が入っていて、そのままローカルでブラウザに食わせると変な画面になるので、ローカルでアプリサーバをあげて、アプリサーバ経由でHTMLをとってきて保存する。
- HTTP GET するファイルのリストは "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\mock" からとってくる。
- html, css, js, 画像ファイル(png, jpg, gif) が対象。
- ディレクトリ構造は再現する。(そうしないと css とかの相対パス指定がおかしくなる)
import os, urllib2, time def get_currenturl(dirpath, root): if dirpath == root: return "/" else: return dirpath[len(root):] def create_url(filename, dirpath, root): return "http://localhost:10080/mock%s" % os.path.join(get_currenturl(dirpath, root), filename).replace("\\", "/") def get_currentpath(root, arg): if arg.startswith(root): return arg[len(root)+1:] def download(filename, basedir, dirpath, root): outpath = os.path.join(basedir, get_currentpath(root, dirpath), filename) content = urllib2.urlopen(create_url(filename, dirpath, root)).read() file(outpath, "wb").write(content) def main(root, basedir): os.mkdir(basedir) for dirpath, dirnames, filenames in os.walk(root): for f in filenames: current = os.path.join(basedir, get_currentpath(root, dirpath)) if not os.path.exists(current): os.makedirs(current) if f[f.rfind("."):] in (".html", ".css", ".js", ".gif", ".jpg", ".png"): download(f, basedir, dirpath, root) if __name__ == "__main__": main("C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\mock", time.strftime('%Y%m%d_%H%M%S'))