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

入力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 に答える