mfernandez

Insert Google Analytics tracker code into html files dir

Aug 2nd, 2011
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import os
  2. import glob
  3.  
  4. """ This little script takes all the static *.html files in the directory being executed and inserts the Google Analytics tracker code. The output html files will be in the 'out' directory.
  5.  
  6. You must set the UA_CODE from your Google Analytics panel.
  7.  
  8. Marcelo Fernández - [email protected]
  9.  
  10. License: Public Domain Code
  11.  
  12. """
  13.  
  14. GA_UA_CODE='UA-00000000-0'
  15. GA_TRACKER_CODE="""<script type="text/javascript">
  16.  
  17.  var _gaq = _gaq || [];
  18.    _gaq.push(['_setAccount', '']);
  19.      _gaq.push(['_trackPageview']);
  20.  
  21.        (function() {
  22.                var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  23.                ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  24.                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  25.              })();
  26.  
  27.        </script>""" % GA_UA_CODE
  28.  
  29.  
  30. if __name__ == '__main__':
  31.     if not os.path.exists('out'):
  32.         os.mkdir('out')
  33.  
  34.     for html in glob.glob('*.html'):
  35.         f = open(html, 'r')
  36.         html_string = f.read()
  37.         f.close()
  38.  
  39.         head_position = html_string.find('</head>')
  40.         if head_position < 0:
  41.             print "There's no head tag in %s" % html
  42.             continue
  43.         new_html = html_string[:head_position-1] + '\n' + GA_TRACKER_CODE + html_string[head_position:]
  44.  
  45.         f = open(os.path.join('out', html), 'w')
  46.         f.write(new_html)
  47.         f.close()
Add Comment
Please, Sign In to add comment