Python Short Url expander

Viewed 1471

i have a problem with expanding short URLs, since not all i work with use the same redirection:

the idea is to expand shortened urls: here a few examples of short url --> Final url. I need a function to get the shorten url and return the expanded url

http://chollo.to/675za --> http://www.elcorteingles.es/limite-48-horas/equipaje/?sorting=priceAsc&aff_id=2118094&dclid=COvjy8Xrz9UCFeMi0wod4ZULuw

So fa i have something semi working, it fails in the some of the abobe examples

import requests
import httplib
import urlparse


def unshorten_url(url):
try:

parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed.netloc)
h.request('HEAD', parsed.path)
response = h.getresponse()

if response.status / 100 == 3 and response.getheader('Location'):
url = requests.get(response.getheader('Location')).url
print url
return url

else:
url = requests.get(url).url
print url
return url


except Exception as e:
print(e)
1 Answers
Related