【发布时间】:2015-06-08 03:23:56
【问题描述】:
当最终的 url 是 https 时,我希望在 python 中取消缩短(解析)一个 url。我已经看到了这个问题:How can I un-shorten a URL using python?(以及类似的其他人),但是正如对已接受答案的评论中所述,此解决方案仅在 URL 未重定向到 https 时才有效。 p>
作为参考,该问题中的代码(在重定向到 http url 时可以正常工作)是:
# This is for Py2k. For Py3k, use http.client and urllib.parse instead, and
# use // instead of / for the division
import httplib
import urlparse
def unshorten_url(url):
parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed.netloc)
resource = parsed.path
if parsed.query != "":
resource += "?" + parsed.query
h.request('HEAD', resource )
response = h.getresponse()
if response.status/100 == 3 and response.getheader('Location'):
return unshorten_url(response.getheader('Location')) # changed to process chains of short urls
else:
return url
(注意 - 出于明显的带宽原因,我希望通过仅询问文件头 [即像上面的 http-only 版本] 而不是询问整个页面的内容来实现)
【问题讨论】:
标签: python python-2.7 url-shortener