Python: Converter os TinyURL (bit.ly, tinyurl, ow.ly) para URLs completas
Pergunta
Eu apenas estou aprendendo Python e está interessado em como isso pode ser feito. Durante a busca para a resposta, me deparei com este serviço: http://www.longurlplease.com
Por exemplo:
http://bit.ly/rgCbf pode ser convertido em:
http://webdesignledger.com/ freebies / the-best-social-media-icons-tudo-em-um-lugar
Eu fiz alguma inspeciona com Firefox e ver que a URL original não está no cabeçalho.
Solução
urllib2
, que oferece a maneira mais fácil de fazer isso:
>>> import urllib2
>>> fp = urllib2.urlopen('http://bit.ly/rgCbf')
>>> fp.geturl()
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
Por amor de referência, no entanto, nota que este também é possível com 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'
E com PycURL
, embora eu não tenho certeza se esta é a melhor maneira de fazê-lo a usá-lo :
>>> 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'
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow