Skip to content

Instantly share code, notes, and snippets.

@vgoklani
Created February 13, 2012 00:08
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save vgoklani/1811970 to your computer and use it in GitHub Desktop.
Save vgoklani/1811970 to your computer and use it in GitHub Desktop.
Expand shortened URLs in Python
# http://stackoverflow.com/questions/748324/python-convert-those-tinyurl-bit-ly-tinyurl-ow-ly-to-full-urls
#############
# urllib2
import urllib2
fp = urllib2.urlopen('http://bit.ly/rgCbf')
fp.geturl()
# ==> 'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
#############
# 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'
#############
# pycurl
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'
@AddaxSoft
Copy link

AddaxSoft commented Jan 19, 2021

# python3


import http.client


def expandURL(link):
    conn = http.client.HTTPSConnection('bit.ly') #use HTTPS !
    conn.request('HEAD', '/foobar')
    response = conn.getresponse()
    return response.getheader('location')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment