python - 当最终网址为 https 时,如何使用 python 取消缩短(解析)网址?

标签 python python-2.7 url-shortener

当最终网址为 https 时,我希望在 python 中取消缩短(解析)网址。我看到了这个问题:How can I un-shorten a URL using python? (以及类似的其他),但是正如对已接受答案的评论中指出的那样,此解决方案仅在 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-only 版本] 而不是通过请求整个页面的内容来实现)

最佳答案

如果 parsed.schemehttps,您可以从 url 获取方案,然后使用 HTTPSConnection .
您也可以使用请求库来非常简单地完成此操作。

>>> import requests
>>> r = requests.head('http://bit.ly/IFHzvO', allow_redirects=True)
>>> print(r.url)
https://www.google.com

关于python - 当最终网址为 https 时,如何使用 python 取消缩短(解析)网址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425378/

相关文章:

Python:ValueError:float() 的无效文字:

python - 如何从Python中的嵌套for循环创建数据框?

php - 马蒂亚斯 URL 缩短器

python - 使用python快速扩展缩短的URL

python - Visual Studio Code 快速修复和 python

python - 尝试拆分为训练/测试集时未找到 X 索引

python - 破解 python 的 import 语句

python - 如何实现泊松回归?

python - Django: href {% url %} 问题

javascript - Node.js - 如何创建可以访问根路径 "/'之前的url的请求