【问题标题】:Unwrapping t.co link that links to bit.ly展开链接到 bit.ly 的 t.co 链接
【发布时间】:2013-02-08 07:37:24
【问题描述】:
我正在尝试获取已经被 bit.ly 和 twitter 缩短的 URL。我已经试过了:
import urllib.request
r = urllib.request.urlopen(url)
r.url
也可以使用 requests 和 httplib2 等库。
如果我想要 t.co 链接的最终目的地,所有这些解决方案都可以工作,但是,我确实需要中间缩短器,我现在可以通过 HEAD 请求获得它,但我无法获得 Python 3 http。客户工作以获取位置。有什么想法吗?
【问题讨论】:
标签:
python
twitter
python-3.x
【解决方案1】:
>>> c = http.client.HTTPConnection('t.co')
>>> c.request('GET', '/7fGoazTYpc') # or HEAD, but body is empty anyway
>>> r = c.getresponse()
>>> r.getheader('Location')
'http://bit.ly/900913'
【解决方案2】:
requests 自动跟随重定向,但它允许您通过 history 属性访问所有 URL。
>>> r = requests.get('http://bit.ly/UG4ECS')
>>> r.url
u'http://www.fontsquirrel.com/fonts/exo'
>>> r.history
(<Response [301]>,)
>>> r.history[0].url
u'http://bit.ly/UG4ECS'
>>>