短縮URLサービスbit.lyを使う
twitterのような140文字制限のある文章内にURLを入れたいときには、短縮URLを使うのが常識だ
python使ってbit.lyの短縮URLを取得するスクリプトを書いてみた。
json形式とXML形式での取得が可能のようだが、今回はJSONを処理することにする。
# coding: utf-8 from urllib2 import urlopen from urllib import urlencode import simplejson as json class bitly(): def __init__(self,login_id,api_key): self.login_id = login_id self.api_key = api_key self.dec = json.JSONDecoder() def shorten(self,url): param = { 'version': '2.0.1', 'longUrl': url, 'login': self.login_id, 'apiKey': self.api_key } res = urlopen('http://api.bit.ly/shorten?'+urlencode(param)) res = self.dec.decode(res.read()) return res['results'][url]['shortUrl']
使い方は以下のとおり。
from bitly import bitly b = bitly([bit.lyのアカウント名],[bit.lyのAppKey]) b.shorten('http://google.com/')
↓このようなURLが取得できます。
http://bit.ly/6FYyOe