Python : Tinyurl (Bit.ly, Tinyurl, OW.Ly)을 전체 URL로 변환
문제
나는 단지 파이썬을 배우고 있으며 이것이 어떻게 달성 될 수 있는지에 관심이 있습니다. 답을 찾는 동안이 서비스를 발견했습니다. http://www.longurlplease.com
예를 들어:
http://bit.ly/rgcbf 다음으로 변환 할 수 있습니다.
http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place
Firefox로 검사를했고 원래 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'
그러나 참조를 위해 이것은 또한 가능하다는 점에 유의합니다. 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'
제휴하지 않습니다 StackOverflow