Skip to content

Instantly share code, notes, and snippets.

@copyninja
Created October 6, 2010 11:08
Show Gist options
  • Save copyninja/613186 to your computer and use it in GitHub Desktop.
Save copyninja/613186 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/python2.6
# Original Post http://segfault.in/2010/10/shorten-urls-using-google-and-python/
from urllib2 import urlopen, Request, HTTPError
from urllib import urlencode
from simplejson import loads
import sys
import re
def shorten_url(url):
"""
url: URL to be shortened
return shortened url
"""
#if not url.startswith("ftp://") and not url.startswith("https://") and not url.startswith("http://"):
if not re.match('^(http|https|ftp):\/\/',url):
# Assume http prefix
url = "http://" + url
try:
request = Request(url="http://goo.gl/api/url")
request.add_header('User-Agent',"Google URL Shortner")
request.add_data(urlencode({'url': url}))
response = urlopen(request)
return loads(response.read())['short_url']
except HTTPError, e:
return loads(e.read())
if __name__ == "__main__":
if len(sys.argv) == 1:
print "Usage: python g_improved.py <url>"
else:
print shorten_url(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment