我只是在学习Python,我对如何完成这一点很感兴趣。在搜索答案的过程中,我遇到了这个服务:http://www.longurlplease.com
例如:
http://bit.ly/rgCbf可转换为:
http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place
我用火狐做了一些检查,发现原始URL不在头中。

最佳答案

输入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'

但是,为了参考起见,请注意,这也可以通过以下方式实现:
>>> 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'

使用httplib,尽管我不确定这是否是使用它的最佳方法:
>>> 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'

关于python - Python:将那些TinyURL(bit.ly,tinyurl,ow.ly)转换为完整的URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/748324/

10-12 23:07