Python:将TinyURL(bit.ly,tinyurl,ow.ly)转换为完整URL

14 投票
1 回答
8157 浏览
提问于 2025-04-15 11:07

我刚开始学习Python,想知道怎么实现这个功能。在寻找答案的过程中,我发现了一个服务:http://www.longurlplease.com

举个例子:

http://bit.ly/rgCbf 可以转换成:

http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place

我用Firefox查看了一下,发现原始网址并不在页面的头部信息里。

1 个回答

32

这里介绍一下 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'

撰写回答