【问题标题】:Unshorten Flic.kr URLs取消缩短 Flic.kr URL
【发布时间】:2015-02-10 07:01:36
【问题描述】:

我有一个 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=[...]

因此最终出现在雅虎登录页面上。顺便说一句,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 URL 的完整工作示例

【问题讨论】:

  • 嗯...这不是完整的脚本,错误可能不在此处。你能去掉一些不重要的部分并发布一个更完整的代码示例吗?
  • 将其更改为可工作的独立脚本

标签: python url flickr url-shortener


【解决方案1】:

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

>>> 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/

【讨论】:

  • 这确实很好,并且使我的方法基本上过时了:)。非常感谢!
猜你喜欢
  • 2011-05-11
  • 2020-05-12
  • 2011-11-01
  • 2020-06-10
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2013-10-20
相关资源
最近更新 更多