Python + goo.gl の API で短縮URL
Googleの短縮URLのAPIが提供されたので、Pythonでとりあえず短縮だけしてみた。
http://code.google.com/intl/ja/apis/urlshortener/v1/getting_started.html
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import simplejson API_URL = 'https://www.googleapis.com/urlshortener/v1/url' API_KEY = None def shorten(longUrl): if isinstance(longUrl, unicode): longUrl = longUrl.encode('utf-8') if API_KEY is None: data = '{longUrl:"%s"}' % (longUrl) else: data = '{longUrl:"%s", key:"%s"}' % (longUrl, API_KEY) req = urllib2.Request(API_URL, data) req.add_header('Content-Type', 'application/json') result = urllib2.urlopen(req) return simplejson.loads(result.read()).get('id') if __name__ == '__main__': print shorten(u'http://ja.wikipedia.org/wiki/うさぎ') print shorten(u'http://ja.uncyclopedia.info/wiki/うさぎ')
結果
http://goo.gl/LyJjn http://goo.gl/MBCBo