Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS

I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: http://www.longurlplease.com

For example:

http://bit.ly/rgCbf can be converted to:

http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place

I did some inspecting with Firefox and see that the original url is not in the header.

like image 881
TimLeung Avatar asked Apr 14 '09 16:04

TimLeung


1 Answers

Enter urllib2, which offers the easiest way of doing this:

>>> import urllib2
>>> fp = urllib2.urlopen('http://bit.ly/rgCbf')
>>> fp.geturl()
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'

For reference's sake, however, note that this is also possible with httplib:

>>> import httplib
>>> conn = httplib.HTTPConnection('bit.ly')
>>> conn.request('HEAD', '/rgCbf')
>>> response = conn.getresponse()
>>> response.getheader('location')
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'

And with PycURL, although I'm not sure if this is the best way to do it using it:

>>> import pycurl
>>> conn = pycurl.Curl()
>>> conn.setopt(pycurl.URL, "http://bit.ly/rgCbf")
>>> conn.setopt(pycurl.FOLLOWLOCATION, 1)
>>> conn.setopt(pycurl.CUSTOMREQUEST, 'HEAD')
>>> conn.setopt(pycurl.NOBODY, True)
>>> conn.perform()
>>> conn.getinfo(pycurl.EFFECTIVE_URL)
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
like image 178
Paolo Bergantino Avatar answered Sep 23 '22 19:09

Paolo Bergantino