当最终的 url 是 https 时,我希望在 python 中取消缩短(解析)一个 url。我看到过这样的问题:如何使用 python 取消缩短 URL? (以及其他类似的),但是正如已接受答案的评论中所述,此解决方案仅在 url 未重定向到 https 时才有效。
作为参考,该问题中的代码(重定向到 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版本]而不是通过询问整个页面的内容来实现)
您可以从以下位置获取该方案url
然后使用HTTPSConnection
if the parsed.scheme
is https
.
您还可以使用 requests 库来非常简单地完成此操作。
>>> import requests
>>> r = requests.head('http://bit.ly/IFHzvO', allow_redirects=True)
>>> print(r.url)
https://www.google.com
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)