shorturl.py: Short a long URL from comand line, in Python


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env python
  2. #
  3. # shorturl.py
  4. # Shorts a long URL from command line, using ur1.ca.
  5. # Shows original page's title and short url.
  6. #
  7. # ksaver, (at identi.ca); Sep, 2010.
  8. # version 0.2, Mar 2011.
  9. # Requieres BeautifulSoup library in order to work properly:
  10. # http://www.crummy.com/software/BeautifulSoup/
  11. #
  12. # Public Domain Code.
  13.  
  14. import sys
  15. import urllib2
  16.  
  17. from BeautifulSoup import BeautifulSoup
  18. from urllib import urlencode
  19.  
  20. def shorten(longurl):
  21. shortener = 'http://ur1.ca/'
  22. urlparam = {'longurl': longurl}
  23. encparam = urlencode(urlparam)
  24. request = urllib2.Request(shortener, encparam)
  25. htmlpage = urllib2.urlopen(request).read()
  26. htmlsoup = BeautifulSoup(htmlpage)
  27. txtmatch = htmlsoup.p.text.find('http')
  28. shorturl = htmlsoup.p.text[txtmatch:]
  29. return shorturl
  30.  
  31. def main(url):
  32. htmldoc = urllib2.urlopen(url).read()
  33. mysoup = BeautifulSoup(htmldoc)
  34. title = mysoup.title.text
  35. shorturl = shorten(url)
  36.  
  37. print "'%s': %s\n" % (title, shorturl)
  38.  
  39. if __name__ == '__main__':
  40. if len(sys.argv) > 1:
  41. url = sys.argv[1]
  42. else:
  43. url = raw_input("URL to short: ")
  44. main(url)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.