スキップしてメイン コンテンツに移動

Python: Google Analyticsのトラッキングコードを複数のHTMLファイルに一括で埋め込む

Google Analyticsは便利だが自前のHTMLファイルが多数あるとトラッキングコードを埋め込むのが面倒だ(ブログだったらテンプレートを変更するだけなんだけどね)。そこで、以下に示すPythonスクリプトで一括で埋め込むことができるようにした。もちろん、階層を持つディレクトリでも問題ない。念のため、バックアップは必ず取っておこう。本スクリプトの使用は自己責任で。

使い方について。まずは、以下に示すソースコードを適当な名前(例えば insert_google_analytics.py)で保存する。次に、トラッキングIDを"UA-xxxxxx-x"から正しいIDに変更する。そして、そのスクリプトをHTMLファイルが保存してあるディレクトリで実行するだけ。もちろん、事前にPythonをインストールしておくこと。

#!/usr/bin/env python import sys, os, re ANALYSTIC_HTML = """<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-xxxxxxx-x"); pageTracker._initData(); pageTracker._trackPageview(); </script> """ def search_web(search_path): html_list = [] for root, dirs, files in os.walk(search_path): for f in files: if os.path.splitext(f)[1] == ".html": html_list.append(os.path.join(root, f)) return html_list def insert_analystics(f): has_analystics = False infile = file(f) in_data = infile.readlines() infile.close() outfile = file(f, "w") out_data = [] for l in in_data: if re.search(r"google-analytics.com/ga.js", l): has_analystics = True search_last_body = re.search(r"(.*)</body>.*", l.lower()) if not has_analystics and search_last_body: s1 = l[:len(search_last_body.group(1))].strip() s2 = l[len(search_last_body.group(1)):].strip() if len(s1) > 0: out_data.append(s1 + "\n") out_data.append(ANALYSTIC_HTML) out_data.append(s2 + "\n") else: out_data.append(l) outfile.writelines(out_data) def main(): html_files = search_web(".") for f in html_files: insert_analystics(f) if __name__ == "__main__": main()

コメント