我有一个Python脚本,它根据发布的答案here取消对url的排序。到目前为止,它工作得很好,例如,youtu.be
,goo.gl
,t.co
,bit.ly
,和{
例如,当我输入URL时
https://flic.kr/p/qf3mGd
在浏览器中,我被正确地重定向到
^{pr2}$但是,当使用Python脚本取消对同一URL的排序时,我得到了以下重定向
^{3}$最终在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')
{cd3>使用完整的URL}示例
我用这种方式使用Request[0]而不是httplib,它可以很好地处理类似于https://flic.kr/p/qf3mGd的URL:
[0]http://docs.python-requests.org/en/latest/
相关问题 更多 >
编程相关推荐