Created
August 17, 2014 17:12
-
-
Save jfrobbins/b4d1662fc26905984412 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #URLshortener | |
| # this class POSTs to http://ur1.ca and then gets the | |
| # returned shortened UR1 from the repsonse | |
| # | |
| #this requires requests and only works with python2 | |
| # https://pypi.python.org/pypi/requests/0.13.0 | |
| import requests | |
| class URLshortener(object): | |
| def __init__(self): | |
| print("init object") | |
| def getURLfromUR1caResponse(self, response): | |
| #response: | |
| #... | |
| #<p class="success">Your ur1 is: <a href="http://ur1.ca/hzm8a">http://ur1.ca/hzm8a</a></p> | |
| #... | |
| prefx = '<p class="success">Your ur1 is: <a href="' | |
| linkClose = '">' | |
| postfx = '</a>' | |
| if not prefx in response: | |
| return "failure" | |
| pos = 0 | |
| pos = response.find(prefx,pos) | |
| if pos < 0: | |
| return "failure" | |
| htmlText = response[pos:response.find(postfx,pos) + len(postfx)] | |
| #print "htmlText:" + htmlText | |
| link = htmlText[htmlText.find(prefx)+len(prefx):] | |
| link = link[:link.find(linkClose)] | |
| print "link: " + link | |
| linkmsg = htmlText[htmlText.find(linkClose)+len(linkClose):htmlText.find(postfx)] | |
| #print "linkmsg: " + linkmsg | |
| return link | |
| def getUR1ca(self, longurl): | |
| payload = {'longurl':longurl} | |
| r = requests.post('http://ur1.ca', data=payload) | |
| print "original URL length: " + str(len(longurl)) | |
| shortURL = self.getURLfromUR1caResponse(r.text) | |
| print "short URL length: " + str(len(shortURL)) | |
| if len(longurl) <= len(shortURL): | |
| return longurl | |
| else: | |
| return shortURL | |
| if __name__ == '__main__': | |
| import sys | |
| myurl = URLshortener() | |
| print myurl.getUR1ca(sys.argv[1]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment