不道德的Flic.kr网址

时间:2015-02-10 07:01:36

标签: python url flickr url-shortener

我有一个Python脚本,可以根据发布的答案here来解除URL。到目前为止,它工作得非常好,例如youtu.begoo.glt.cobit.lytinyurl.com。但现在我注意到它不适用于Flickr自己的URL缩短器flic.kr.

例如,当我输入网址

https://flic.kr/p/qf3mGd

进入浏览器,我被正确地重定向到

https://www.flickr.com/photos/106783633@N02/15911453212/

但是,当使用Python脚本取消相同的URL时,我得到以下重定向

https://flic.kr/p/qf3mgd
http://www.flickr.com/photo.gne?short=qf3mgd
http://www.flickr.com/signin/?acf=%2Fphoto.gne%3Fshort%3Dqf3mgd
https://login.yahoo.com/config/login?.src=flickrsignin&.pc=8190&.scrumb=[...]

因此最终在Yahoo登录页面上结束。顺便说一下,Unshort.me可以正确地取消URL。我在这里缺少什么?

以下是我的脚本的完整源代码。我在原始剧本中偶然发现了一些病态案例:

import urlparse
import httplib


def unshorten_url(url, max_tries=10):
    return __unshorten_url(url, [], max_tries)

def __unshorten_url(url, check_urls, max_tries):
    if max_tries == 0:
        if len(check_urls) > 0:
            return check_urls[0]
        return url
    if url in check_urls:
        return url
    unshortended = ''
    try:
        parsed = urlparse.urlparse(url)
        h = httplib.HTTPConnection(parsed.netloc)
        h.request('HEAD', url)
    except:
        return None
    try:
        response = h.getresponse()
    except:
        return url


    if response.status/100 == 3 and response.getheader('Location'):
        unshortended = response.getheader('Location')
    else:
        return url
    #print max_tries, unshortended
    if unshortended != url:
        if 'http' not in unshortended:
            return url
        check_urls.append(url)
        return __unshorten_url(unshortended, check_urls, (max_tries-1))
    else:
        return unshortended

print unshorten_url('http://t.co/5skmePb7gp')

编辑:包含t.co网址的完整工作示例

1 个答案:

答案 0 :(得分:3)

我以这种方式使用Request [0]而不是httplib,它可以与https://flic.kr/p/qf3mGd一样正常工作:

>>> import requests
>>> requests.head("https://flic.kr/p/qf3mGd", allow_redirects=True, verify=False).url
u'https://www.flickr.com/photos/106783633@N02/15911453212/'

[0] http://docs.python-requests.org/en/latest/