Home > PYTHON > Shorten URLs using goo.gl and Python

Shorten URLs using goo.gl and Python

October 1st, 2010

As we all know it, Google has its own URL shortening service called goo.gl. Google’s URL shortener still doesn’t have an official API and it doesn’t offer all the features that are available at bit.ly, but it works well.

Here is a Python script to shorten URL using goo.gl.

#!/usr/bin/python
# use Google's http://goo.gl/ URL shortener
# requires urllib, urllib2, re, simplejson
def shorten(url):
  try:
    from re import match
    from urllib2 import urlopen, Request, HTTPError
    from urllib import quote
    from simplejson import loads
  except ImportError, e:
    raise Exception('Required module missing: %s' % e.args[0])
  if not match('http://',url):
    raise Exception('URL must start with "http://"')
  try:
    urlopen(Request('http://goo.gl/api/url','url=%s'%quote(url),{'User-Agent':'toolbar'}))
  except HTTPError, e:
    j = loads(e.read())
    if 'short_url' not in j:
      try:
        from pprint import pformat
        j = pformat(j)
      except ImportError:
        j = j.__dict__
      raise Exception('Didn\'t get a correct-looking response. How\'s it look to you?\n\n%s'%j)
    return j['short_url']
  raise Exception('Unknown eror forming short URL.')
 
if __name__ == '__main__':
  from sys import argv
  print shorten(argv[1])

Usage:

$ python g.py http://segfault.in
http://goo.gl/Uh5h

Update:
Expand URLs

def expand(url):
  try:
    import urllib
  except ImportError, e:
    raise Exception('Required module missing: %s' % e.args[0])
 
  f = urllib.urlopen(url)
  return f.geturl()
Categories: PYTHON Tags: , ,
  1. Q
    October 5th, 2010 at 08:27 | #1

    Could you do the same thing with bit.ly or other shortening services ?

    Google may be trying to get maximum information about who is browsing through which URLs, by tapping into the URL shortening services. Why make it even easier for Google ? ;)

  2. Arpit
    February 3rd, 2011 at 13:07 | #3

    may I use the above script for my project? No license information is available in the post.

    • vinod
      February 3rd, 2011 at 14:05 | #4

      sure.

  1. October 4th, 2010 at 03:39 | #1
Comments are closed.