pythonhttp-redirecttinyurl

Find tiny url final redirected url


I have followed several other questions in SO to find the final redirect url, however for the following url I can't make the redirect work. It doesn't redirect and stays at tinyurl.

import urllib2
def getFinalUrl(start_url):
        var = urllib2.urlopen(start_url)
        final_url = var.geturl()
        return final_url


url = "http://redirect.tinyurl.com/api/click?key=a7e37b5f6ff1de9cb410158b1013e54a&out=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fprofile%2FA3B4EO22KUPKYW&loc=&cuid=0072ce987ebb47328d22e465a051ce7&opt=false&format=txt"
redirect = getFinalUrl(url)
print "redirect: " + redirect

the result (which is not the final url if you try in a browser):

redirect: http://redirect.tinyurl.com/api/click?key=a7e37b5f6ff1de9cb410158b1013e54a&out=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fprofile%2FA3B4EO22KUPKYW&loc=&cuid=0072ce987ebb47328d22e465a051ce7&opt=false&format=txt

Solution

  • import urlparse
    url = 'http://redirect.tinyurl.com/api/click?key=a7e37b5f6ff1de9cb410158b1013e54a&out=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fprofile%2FA3B4EO22KUPKYW&loc=&cuid=0072ce987ebb47328d22e465a051ce7&opt=false&format=txt'
    try:
        out = urlparse.parse_qs(urlparse.urlparse(url).query)['out'][0]
        print(out) #http://www.amazon.com/gp/profile/A3B4EO22KUPKYW
    except Exception as e: # dont catch all
        print('not found')
    

    This kind of url does not need to be curled to find out what the destination/redirect url is, well, because you ALREADY have them in your url.


    If the destination/redirect url is not shown like this guy

    tinyurl.com/xxxx

    then that's a different story, you'd have to curl it to find out what it resolves/304 to like below:

    import requests
    url = 'http://urlshortener.com/applebanana'
    t = requests.get(url)
    print(t.url)