user2293094 user2293094 - 2 months ago 21
HTML Question

Using python to expand a bit.ly link

How can I use Python to take a bit.ly link and return the fully expanded link?

If the link inputted is not a bit.ly link, the original link should be returned.

Answer

Python 2:

>>> import urllib2
>>> print urllib2.urlopen('http://bit.ly/1cPIdPg').url
http://stackoverflow.com/

You can also use the geturl() method:

>>> import urllib2
>>> print urllib2.urlopen('http://bit.ly/1cPIdPg').geturl()

And, for Python 3:

>>> from urllib.request import urlopen
>>> print(urlopen('http://bit.ly/1cPIdPg').geturl())
http://stackoverflow.com/
Comments