13

我只是在学习 python,并且对如何实现这一点很感兴趣。在寻找答案的过程中,我遇到了这个服务:http ://www.longurlplease.com

例如:

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

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

我用 Firefox 进行了一些检查,发现原始 url 不在标题中。

4

1 回答 1

33

Enter 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'
于 2009-04-14T16:17:56.877 回答