Skip to content

Instantly share code, notes, and snippets.

@zhao-ji
Created July 12, 2018 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhao-ji/2899ab3fae4417af04264a64d0aaf769 to your computer and use it in GitHub Desktop.
Save zhao-ji/2899ab3fae4417af04264a64d0aaf769 to your computer and use it in GitHub Desktop.
recurse unshorten url
# This is for Py2k. For Py3k, use http.client and urllib.parse instead, and
# use // instead of / for the division
import httplib
import urlparse
def unshorten_url(url):
parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed.netloc)
resource = parsed.path
if parsed.query != "":
resource += "?" + parsed.query
h.request('HEAD', resource )
response = h.getresponse()
if response.status/100 == 3 and response.getheader('Location'):
return unshorten_url(response.getheader('Location')) # changed to process chains of short urls
else:
return url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment