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('')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博客 ” ,链接:https://blog.itpub.net/301743/viewspace-734053/
,如需转载,请注明出处,否则将追究法律责任。