Using Python to Shorten a URL Using Google's Shortening Service

jieforest發表於2012-06-28
Using Python to shorten a URL with Google's shortening service (goo.gl):

CODE:

01.#!/usr/bin/python
02.#  Corey Goldberg - 2010
03.
04.import json
05.import urllib
06.import urllib2
07.
08.
09.def shorten(url):
10.gurl = 'http://goo.gl/api/url?url=%s' % urllib.quote(url)
11.req = urllib2.Request(gurl, data='')
12.req.add_header('User-Agent', 'toolbar')
13.results = json.load(urllib2.urlopen(req))
14.return results['short_url']
15.
16.
17.if __name__ == '__main__':
18.print shorten('http://www.goldb.org/')
19.print shorten('www.yahoo.com')You give it a URL to shorten: shorten('http://www.goldb.org/long_url')

... and it returns a shortened URL for you: 'http://goo.gl/jh4W'

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-734053/,如需轉載,請註明出處,否則將追究法律責任。

相關文章