Created
October 30, 2011 22:38
-
-
Save JeromeParadis/1326548 to your computer and use it in GitHub Desktop.
Strip Google Analytics tracking codes from URL query parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DISCARD = [ | |
'utm_source', | |
'utm_medium', | |
'utm_campaign', | |
'utm_term', | |
'utm_content', | |
] | |
def strip_url_tracking(url): | |
""" | |
Removes Google Analytics codes from URLs | |
Example: | |
strip_url_tracking('http://buyosphere.com/?page=1&utm_source=abc&') -> 'http://buyosphere.com/?page=1=abc&' | |
""" | |
try: | |
from urlparse import urlsplit | |
parts = urlsplit(url) | |
if parts.query and len(parts.query) > 0: | |
new_query = '&'.join([part for part in parts.query.split('&') if part.split('=')[0] not in DISCARD]) | |
new_url = '%s://%s%s' % (parts.scheme,parts.netloc,parts.path) | |
if new_query and len(new_query) > 0: | |
new_url = '%s?%s' % (new_url,new_query) | |
return new_url | |
except: | |
pass | |
return url |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment