-1

I am using this code for unshortening urls in python 3 , but the code returns the url as it is (shortened), so what should I do to get it unshortened?

import requests
import http.client
import urllib.parse as urlparse   

def unshortenurl(url):
    parsed = urlparse.urlparse(url) 
    h = http.client.HTTPConnection(parsed.netloc) 
    h.request('HEAD', parsed.path) 
    response = h.getresponse() 
    if response.status/100 == 3 and response.getheader('Location'):
        return response.getheader('Location') 
    else: return url
Youcef
  • 1,103
  • 2
  • 11
  • 26

1 Answers1

1

In python3 response.status/100 == 3 would be True only for status code 300. For any other 3xx code it would be False. Use floor division instead response.status//100 == 3 or some other way to test for redirection codes.

EDIT: It looks you are using the code from SO question posted by @Aybars and there is comment at the top of the snippet what to do in python3. Also, it would have been nice to mention the source of the code.

buran
  • 13,682
  • 10
  • 36
  • 61
  • Tried to change response.status/100 == 3 to response.status//100 == 3 but did not solve the problem – Youcef Dec 11 '18 at 07:55
  • Check the comment at the top of the code from original SO question – buran Dec 11 '18 at 07:56
  • Thanks for the clarification, is there a way to check if the url is shortened or not, so that I unshorten only the shortened ones in order to gain time! – Youcef Dec 11 '18 at 08:21