Skip to content

Instantly share code, notes, and snippets.

@brettkelly
Created July 15, 2012 04:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save brettkelly/3114989 to your computer and use it in GitHub Desktop.
Save brettkelly/3114989 to your computer and use it in GitHub Desktop.
Python to rework Amazon URL to contain the user's affiliate code
#!/usr/bin/env python
# (c) 2012 Brett Kelly.
# Licensed under the MIT license
# http://www.opensource.org/licenses/mit-license.php
import re
import sys
from urlparse import urlparse
## PUT YOUR AFFILIATE CODE HERE
affcode = 'nerdgap-20'
rawurl = '%clipboard'.strip()
## Get the base url without all of the query string malarky
baseurl = rawurl.split('?')[0]
try:
parts = urlparse(baseurl)
except Exception:
sys.stdout.write(rawurl)
raise SystemExit
## Make sure it's actually an Amazon URL
amazonre = re.compile('[www\.]{0,1}amazon\.')
if not amazonre.search(parts.netloc):
# Not an amazon URL, return whatever was passed initially
sys.stdout.write(rawurl)
raise SystemExit
# Format the simpler URL and append the affiliate code
goodurl = "%s://%s%s?tag=%s" % (parts.scheme,parts.netloc,parts.path,affcode)
# Write formatted URL to STDOUT
sys.stdout.write(goodurl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment